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,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/AccessorDeclarationStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
public class AccessorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<AccessorDeclarationSyntax>
{
protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
internal override AbstractSyntaxStructureProvider CreateProvider() => new AccessorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetter3()
{
const string code = @"
class C
{
public string Text
{
$${|#0:get{|textspan:
{
}|#0}
|}
set
{
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetterWithSingleLineComments3()
{
const string code = @"
class C
{
public string Text
{
{|span1:// My
// Getter|}
$${|#0:get{|textspan2:
{
}|#0}
|}
set
{
}
}
}
";
await VerifyBlockSpansAsync(code,
Region("span1", "// My ...", autoCollapse: true),
Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetterWithMultiLineComments3()
{
const string code = @"
class C
{
public string Text
{
{|span1:/* My
Getter */|}
$${|#0:get{|textspan2:
{
}|#0}
|}
set
{
}
}
}
";
await VerifyBlockSpansAsync(code,
Region("span1", "/* My ...", autoCollapse: true),
Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
public class AccessorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<AccessorDeclarationSyntax>
{
protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
internal override AbstractSyntaxStructureProvider CreateProvider() => new AccessorDeclarationStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetter3()
{
const string code = @"
class C
{
public string Text
{
$${|#0:get{|textspan:
{
}|#0}
|}
set
{
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetterWithSingleLineComments3()
{
const string code = @"
class C
{
public string Text
{
{|span1:// My
// Getter|}
$${|#0:get{|textspan2:
{
}|#0}
|}
set
{
}
}
}
";
await VerifyBlockSpansAsync(code,
Region("span1", "// My ...", autoCollapse: true),
Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestPropertyGetterWithMultiLineComments3()
{
const string code = @"
class C
{
public string Text
{
{|span1:/* My
Getter */|}
$${|#0:get{|textspan2:
{
}|#0}
|}
set
{
}
}
}
";
await VerifyBlockSpansAsync(code,
Region("span1", "/* My ...", autoCollapse: true),
Region("textspan2", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/Symbols/NamespaceKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Describes the kind of the namespace extent.
/// </summary>
public enum NamespaceKind
{
Module = 1,
Assembly = 2,
Compilation = 3
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Describes the kind of the namespace extent.
/// </summary>
public enum NamespaceKind
{
Module = 1,
Assembly = 2,
Compilation = 3
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/XunitHook/XunitDisposeHook.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal sealed class XunitDisposeHook : MarshalByRefObject
{
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")]
public void Execute()
{
if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
throw new InvalidOperationException();
var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray();
foreach (var xunitUtility in xunitUtilities)
{
var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain");
if (appDomainManagerType is null)
continue;
// AppDomainManager_AppDomain.Dispose() calls AppDomain.Unload(), which is unfortunately not reliable
// when the test creates STA COM objects. Since this call to Unload() only occurs at the end of testing
// (immediately before the process is going to close anyway), we can simply hot-patch the executable
// code in Dispose() to return without taking any action.
//
// This is a workaround for https://github.com/xunit/xunit/issues/2097. The fix in
// https://github.com/xunit/xunit/pull/2192 was not viable because xunit v2 is no longer shipping
// updates. Once xunit v3 is available, it will no longer be necessary.
var method = appDomainManagerType.GetMethod("Dispose");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
var functionPointer = method.MethodHandle.GetFunctionPointer();
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X86:
case Architecture.X64:
// 😱 Overwrite the compiled method to just return.
// Note that the same sequence works for x86 and x64.
// ret
Marshal.WriteByte(functionPointer, 0xC3);
break;
default:
throw new NotSupportedException();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal sealed class XunitDisposeHook : MarshalByRefObject
{
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Invoked across app domains")]
public void Execute()
{
if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
throw new InvalidOperationException();
var xunitUtilities = AppDomain.CurrentDomain.GetAssemblies().Where(static assembly => assembly.GetName().Name.StartsWith("xunit.runner.utility")).ToArray();
foreach (var xunitUtility in xunitUtilities)
{
var appDomainManagerType = xunitUtility.GetType("Xunit.AppDomainManager_AppDomain");
if (appDomainManagerType is null)
continue;
// AppDomainManager_AppDomain.Dispose() calls AppDomain.Unload(), which is unfortunately not reliable
// when the test creates STA COM objects. Since this call to Unload() only occurs at the end of testing
// (immediately before the process is going to close anyway), we can simply hot-patch the executable
// code in Dispose() to return without taking any action.
//
// This is a workaround for https://github.com/xunit/xunit/issues/2097. The fix in
// https://github.com/xunit/xunit/pull/2192 was not viable because xunit v2 is no longer shipping
// updates. Once xunit v3 is available, it will no longer be necessary.
var method = appDomainManagerType.GetMethod("Dispose");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
var functionPointer = method.MethodHandle.GetFunctionPointer();
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X86:
case Architecture.X64:
// 😱 Overwrite the compiled method to just return.
// Note that the same sequence works for x86 and x64.
// ret
Marshal.WriteByte(functionPointer, 0xC3);
break;
default:
throw new NotSupportedException();
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.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.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class EventDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
eventDeclaration As EventStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(eventDeclaration, spans, optionProvider)
Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax)
If Not block?.EndEventStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=eventDeclaration, autoCollapse:=True,
type:=BlockTypes.Member, isCollapsible:=True))
CollectCommentsRegions(block.EndEventStatement, spans, optionProvider)
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.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class EventDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
eventDeclaration As EventStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(eventDeclaration, spans, optionProvider)
Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax)
If Not block?.EndEventStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=eventDeclaration, autoCollapse:=True,
type:=BlockTypes.Member, isCollapsible:=True))
CollectCommentsRegions(block.EndEventStatement, spans, optionProvider)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/MetadataReference/MetadataReferenceProperties.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information about a metadata reference.
/// </summary>
public struct MetadataReferenceProperties : IEquatable<MetadataReferenceProperties>
{
private readonly MetadataImageKind _kind;
private readonly ImmutableArray<string> _aliases;
private readonly bool _embedInteropTypes;
/// <summary>
/// Default properties for a module reference.
/// </summary>
public static MetadataReferenceProperties Module => new MetadataReferenceProperties(MetadataImageKind.Module);
/// <summary>
/// Default properties for an assembly reference.
/// </summary>
public static MetadataReferenceProperties Assembly => new MetadataReferenceProperties(MetadataImageKind.Assembly);
/// <summary>
/// Initializes reference properties.
/// </summary>
/// <param name="kind">The image kind - assembly or module.</param>
/// <param name="aliases">Assembly aliases. Can't be set for a module.</param>
/// <param name="embedInteropTypes">True to embed interop types from the referenced assembly to the referencing compilation. Must be false for a module.</param>
public MetadataReferenceProperties(MetadataImageKind kind = MetadataImageKind.Assembly, ImmutableArray<string> aliases = default, bool embedInteropTypes = false)
{
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
if (kind == MetadataImageKind.Module)
{
if (embedInteropTypes)
{
throw new ArgumentException(CodeAnalysisResources.CannotEmbedInteropTypesFromModule, nameof(embedInteropTypes));
}
if (!aliases.IsDefaultOrEmpty)
{
throw new ArgumentException(CodeAnalysisResources.CannotAliasModule, nameof(aliases));
}
}
if (!aliases.IsDefaultOrEmpty)
{
foreach (var alias in aliases)
{
if (!alias.IsValidClrTypeName())
{
throw new ArgumentException(CodeAnalysisResources.InvalidAlias, nameof(aliases));
}
}
}
_kind = kind;
_aliases = aliases;
_embedInteropTypes = embedInteropTypes;
HasRecursiveAliases = false;
}
internal MetadataReferenceProperties(MetadataImageKind kind, ImmutableArray<string> aliases, bool embedInteropTypes, bool hasRecursiveAliases)
: this(kind, aliases, embedInteropTypes)
{
HasRecursiveAliases = hasRecursiveAliases;
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with specified aliases.
/// </summary>
/// <exception cref="ArgumentException">
/// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased.
/// </exception>
public MetadataReferenceProperties WithAliases(IEnumerable<string> aliases)
{
return WithAliases(aliases.AsImmutableOrEmpty());
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with specified aliases.
/// </summary>
/// <exception cref="ArgumentException">
/// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased.
/// </exception>
public MetadataReferenceProperties WithAliases(ImmutableArray<string> aliases)
{
return new MetadataReferenceProperties(_kind, aliases, _embedInteropTypes, HasRecursiveAliases);
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with <see cref="EmbedInteropTypes"/> set to specified value.
/// </summary>
/// <exception cref="ArgumentException"><see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as interop types can't be embedded from modules.</exception>
public MetadataReferenceProperties WithEmbedInteropTypes(bool embedInteropTypes)
{
return new MetadataReferenceProperties(_kind, _aliases, embedInteropTypes, HasRecursiveAliases);
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with <see cref="HasRecursiveAliases"/> set to specified value.
/// </summary>
internal MetadataReferenceProperties WithRecursiveAliases(bool value)
{
return new MetadataReferenceProperties(_kind, _aliases, _embedInteropTypes, value);
}
/// <summary>
/// The image kind (assembly or module) the reference refers to.
/// </summary>
public MetadataImageKind Kind => _kind;
/// <summary>
/// Alias that represents a global declaration space.
/// </summary>
/// <remarks>
/// Namespaces in references whose <see cref="Aliases"/> contain <see cref="GlobalAlias"/> are available in global declaration space.
/// </remarks>
public static string GlobalAlias => "global";
/// <summary>
/// Aliases for the metadata reference. Empty if the reference has no aliases.
/// </summary>
/// <remarks>
/// In C# these aliases can be used in "extern alias" syntax to disambiguate type names.
/// </remarks>
public ImmutableArray<string> Aliases
{
get
{
// Simplify usage - we can't avoid the _aliases field being null but we can always return empty array here:
return _aliases.NullToEmpty();
}
}
/// <summary>
/// True if interop types defined in the referenced metadata should be embedded into the compilation referencing the metadata.
/// </summary>
public bool EmbedInteropTypes => _embedInteropTypes;
/// <summary>
/// True to apply <see cref="Aliases"/> recursively on the target assembly and on all its transitive dependencies.
/// False to apply <see cref="Aliases"/> only on the target assembly.
/// </summary>
internal bool HasRecursiveAliases { get; private set; }
public override bool Equals(object? obj)
{
return obj is MetadataReferenceProperties && Equals((MetadataReferenceProperties)obj);
}
public bool Equals(MetadataReferenceProperties other)
{
return Aliases.SequenceEqual(other.Aliases)
&& _embedInteropTypes == other._embedInteropTypes
&& _kind == other._kind
&& HasRecursiveAliases == other.HasRecursiveAliases;
}
public override int GetHashCode()
{
return Hash.Combine(Hash.CombineValues(Aliases), Hash.Combine(_embedInteropTypes, Hash.Combine(HasRecursiveAliases, _kind.GetHashCode())));
}
public static bool operator ==(MetadataReferenceProperties left, MetadataReferenceProperties right)
{
return left.Equals(right);
}
public static bool operator !=(MetadataReferenceProperties left, MetadataReferenceProperties right)
{
return !left.Equals(right);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information about a metadata reference.
/// </summary>
public struct MetadataReferenceProperties : IEquatable<MetadataReferenceProperties>
{
private readonly MetadataImageKind _kind;
private readonly ImmutableArray<string> _aliases;
private readonly bool _embedInteropTypes;
/// <summary>
/// Default properties for a module reference.
/// </summary>
public static MetadataReferenceProperties Module => new MetadataReferenceProperties(MetadataImageKind.Module);
/// <summary>
/// Default properties for an assembly reference.
/// </summary>
public static MetadataReferenceProperties Assembly => new MetadataReferenceProperties(MetadataImageKind.Assembly);
/// <summary>
/// Initializes reference properties.
/// </summary>
/// <param name="kind">The image kind - assembly or module.</param>
/// <param name="aliases">Assembly aliases. Can't be set for a module.</param>
/// <param name="embedInteropTypes">True to embed interop types from the referenced assembly to the referencing compilation. Must be false for a module.</param>
public MetadataReferenceProperties(MetadataImageKind kind = MetadataImageKind.Assembly, ImmutableArray<string> aliases = default, bool embedInteropTypes = false)
{
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
if (kind == MetadataImageKind.Module)
{
if (embedInteropTypes)
{
throw new ArgumentException(CodeAnalysisResources.CannotEmbedInteropTypesFromModule, nameof(embedInteropTypes));
}
if (!aliases.IsDefaultOrEmpty)
{
throw new ArgumentException(CodeAnalysisResources.CannotAliasModule, nameof(aliases));
}
}
if (!aliases.IsDefaultOrEmpty)
{
foreach (var alias in aliases)
{
if (!alias.IsValidClrTypeName())
{
throw new ArgumentException(CodeAnalysisResources.InvalidAlias, nameof(aliases));
}
}
}
_kind = kind;
_aliases = aliases;
_embedInteropTypes = embedInteropTypes;
HasRecursiveAliases = false;
}
internal MetadataReferenceProperties(MetadataImageKind kind, ImmutableArray<string> aliases, bool embedInteropTypes, bool hasRecursiveAliases)
: this(kind, aliases, embedInteropTypes)
{
HasRecursiveAliases = hasRecursiveAliases;
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with specified aliases.
/// </summary>
/// <exception cref="ArgumentException">
/// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased.
/// </exception>
public MetadataReferenceProperties WithAliases(IEnumerable<string> aliases)
{
return WithAliases(aliases.AsImmutableOrEmpty());
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with specified aliases.
/// </summary>
/// <exception cref="ArgumentException">
/// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased.
/// </exception>
public MetadataReferenceProperties WithAliases(ImmutableArray<string> aliases)
{
return new MetadataReferenceProperties(_kind, aliases, _embedInteropTypes, HasRecursiveAliases);
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with <see cref="EmbedInteropTypes"/> set to specified value.
/// </summary>
/// <exception cref="ArgumentException"><see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as interop types can't be embedded from modules.</exception>
public MetadataReferenceProperties WithEmbedInteropTypes(bool embedInteropTypes)
{
return new MetadataReferenceProperties(_kind, _aliases, embedInteropTypes, HasRecursiveAliases);
}
/// <summary>
/// Returns <see cref="MetadataReferenceProperties"/> with <see cref="HasRecursiveAliases"/> set to specified value.
/// </summary>
internal MetadataReferenceProperties WithRecursiveAliases(bool value)
{
return new MetadataReferenceProperties(_kind, _aliases, _embedInteropTypes, value);
}
/// <summary>
/// The image kind (assembly or module) the reference refers to.
/// </summary>
public MetadataImageKind Kind => _kind;
/// <summary>
/// Alias that represents a global declaration space.
/// </summary>
/// <remarks>
/// Namespaces in references whose <see cref="Aliases"/> contain <see cref="GlobalAlias"/> are available in global declaration space.
/// </remarks>
public static string GlobalAlias => "global";
/// <summary>
/// Aliases for the metadata reference. Empty if the reference has no aliases.
/// </summary>
/// <remarks>
/// In C# these aliases can be used in "extern alias" syntax to disambiguate type names.
/// </remarks>
public ImmutableArray<string> Aliases
{
get
{
// Simplify usage - we can't avoid the _aliases field being null but we can always return empty array here:
return _aliases.NullToEmpty();
}
}
/// <summary>
/// True if interop types defined in the referenced metadata should be embedded into the compilation referencing the metadata.
/// </summary>
public bool EmbedInteropTypes => _embedInteropTypes;
/// <summary>
/// True to apply <see cref="Aliases"/> recursively on the target assembly and on all its transitive dependencies.
/// False to apply <see cref="Aliases"/> only on the target assembly.
/// </summary>
internal bool HasRecursiveAliases { get; private set; }
public override bool Equals(object? obj)
{
return obj is MetadataReferenceProperties && Equals((MetadataReferenceProperties)obj);
}
public bool Equals(MetadataReferenceProperties other)
{
return Aliases.SequenceEqual(other.Aliases)
&& _embedInteropTypes == other._embedInteropTypes
&& _kind == other._kind
&& HasRecursiveAliases == other.HasRecursiveAliases;
}
public override int GetHashCode()
{
return Hash.Combine(Hash.CombineValues(Aliases), Hash.Combine(_embedInteropTypes, Hash.Combine(HasRecursiveAliases, _kind.GetHashCode())));
}
public static bool operator ==(MetadataReferenceProperties left, MetadataReferenceProperties right)
{
return left.Equals(right);
}
public static bool operator !=(MetadataReferenceProperties left, MetadataReferenceProperties right)
{
return !left.Equals(right);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Portable/Errors/MessageID.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum MessageID
{
None = 0,
MessageBase = 1200,
IDS_SK_METHOD = MessageBase + 2000,
IDS_SK_TYPE = MessageBase + 2001,
IDS_SK_NAMESPACE = MessageBase + 2002,
IDS_SK_FIELD = MessageBase + 2003,
IDS_SK_PROPERTY = MessageBase + 2004,
IDS_SK_UNKNOWN = MessageBase + 2005,
IDS_SK_VARIABLE = MessageBase + 2006,
IDS_SK_EVENT = MessageBase + 2007,
IDS_SK_TYVAR = MessageBase + 2008,
//IDS_SK_GCLASS = MessageBase + 2009,
IDS_SK_ALIAS = MessageBase + 2010,
//IDS_SK_EXTERNALIAS = MessageBase + 2011,
IDS_SK_LABEL = MessageBase + 2012,
IDS_SK_CONSTRUCTOR = MessageBase + 2013,
IDS_NULL = MessageBase + 10001,
//IDS_RELATEDERROR = MessageBase + 10002,
//IDS_RELATEDWARNING = MessageBase + 10003,
IDS_XMLIGNORED = MessageBase + 10004,
IDS_XMLIGNORED2 = MessageBase + 10005,
IDS_XMLFAILEDINCLUDE = MessageBase + 10006,
IDS_XMLBADINCLUDE = MessageBase + 10007,
IDS_XMLNOINCLUDE = MessageBase + 10008,
IDS_XMLMISSINGINCLUDEFILE = MessageBase + 10009,
IDS_XMLMISSINGINCLUDEPATH = MessageBase + 10010,
IDS_GlobalNamespace = MessageBase + 10011,
IDS_FeatureGenerics = MessageBase + 12500,
IDS_FeatureAnonDelegates = MessageBase + 12501,
IDS_FeatureModuleAttrLoc = MessageBase + 12502,
IDS_FeatureGlobalNamespace = MessageBase + 12503,
IDS_FeatureFixedBuffer = MessageBase + 12504,
IDS_FeaturePragma = MessageBase + 12505,
IDS_FOREACHLOCAL = MessageBase + 12506,
IDS_USINGLOCAL = MessageBase + 12507,
IDS_FIXEDLOCAL = MessageBase + 12508,
IDS_FeatureStaticClasses = MessageBase + 12511,
IDS_FeaturePartialTypes = MessageBase + 12512,
IDS_MethodGroup = MessageBase + 12513,
IDS_AnonMethod = MessageBase + 12514,
IDS_FeatureSwitchOnBool = MessageBase + 12517,
//IDS_WarnAsError = MessageBase + 12518,
IDS_Collection = MessageBase + 12520,
IDS_FeaturePropertyAccessorMods = MessageBase + 12522,
IDS_FeatureExternAlias = MessageBase + 12523,
IDS_FeatureIterators = MessageBase + 12524,
IDS_FeatureDefault = MessageBase + 12525,
IDS_FeatureNullable = MessageBase + 12528,
IDS_Lambda = MessageBase + 12531,
IDS_FeaturePatternMatching = MessageBase + 12532,
IDS_FeatureThrowExpression = MessageBase + 12533,
IDS_FeatureImplicitArray = MessageBase + 12557,
IDS_FeatureImplicitLocal = MessageBase + 12558,
IDS_FeatureAnonymousTypes = MessageBase + 12559,
IDS_FeatureAutoImplementedProperties = MessageBase + 12560,
IDS_FeatureObjectInitializer = MessageBase + 12561,
IDS_FeatureCollectionInitializer = MessageBase + 12562,
IDS_FeatureLambda = MessageBase + 12563,
IDS_FeatureQueryExpression = MessageBase + 12564,
IDS_FeatureExtensionMethod = MessageBase + 12565,
IDS_FeaturePartialMethod = MessageBase + 12566,
IDS_FeatureDynamic = MessageBase + 12644,
IDS_FeatureTypeVariance = MessageBase + 12645,
IDS_FeatureNamedArgument = MessageBase + 12646,
IDS_FeatureOptionalParameter = MessageBase + 12647,
IDS_FeatureExceptionFilter = MessageBase + 12648,
IDS_FeatureAutoPropertyInitializer = MessageBase + 12649,
IDS_SK_TYPE_OR_NAMESPACE = MessageBase + 12652,
IDS_Contravariant = MessageBase + 12659,
IDS_Contravariantly = MessageBase + 12660,
IDS_Covariant = MessageBase + 12661,
IDS_Covariantly = MessageBase + 12662,
IDS_Invariantly = MessageBase + 12663,
IDS_FeatureAsync = MessageBase + 12668,
IDS_FeatureStaticAnonymousFunction = MessageBase + 12669,
IDS_LIB_ENV = MessageBase + 12680,
IDS_LIB_OPTION = MessageBase + 12681,
IDS_REFERENCEPATH_OPTION = MessageBase + 12682,
IDS_DirectoryDoesNotExist = MessageBase + 12683,
IDS_DirectoryHasInvalidPath = MessageBase + 12684,
IDS_Namespace1 = MessageBase + 12685,
IDS_PathList = MessageBase + 12686,
IDS_Text = MessageBase + 12687,
IDS_FeatureDiscards = MessageBase + 12688,
IDS_FeatureDefaultTypeParameterConstraint = MessageBase + 12689,
IDS_FeatureNullPropagatingOperator = MessageBase + 12690,
IDS_FeatureExpressionBodiedMethod = MessageBase + 12691,
IDS_FeatureExpressionBodiedProperty = MessageBase + 12692,
IDS_FeatureExpressionBodiedIndexer = MessageBase + 12693,
// IDS_VersionExperimental = MessageBase + 12694,
IDS_FeatureNameof = MessageBase + 12695,
IDS_FeatureDictionaryInitializer = MessageBase + 12696,
IDS_ToolName = MessageBase + 12697,
IDS_LogoLine1 = MessageBase + 12698,
IDS_LogoLine2 = MessageBase + 12699,
IDS_CSCHelp = MessageBase + 12700,
IDS_FeatureUsingStatic = MessageBase + 12701,
IDS_FeatureInterpolatedStrings = MessageBase + 12702,
IDS_OperationCausedStackOverflow = MessageBase + 12703,
IDS_AwaitInCatchAndFinally = MessageBase + 12704,
IDS_FeatureReadonlyAutoImplementedProperties = MessageBase + 12705,
IDS_FeatureBinaryLiteral = MessageBase + 12706,
IDS_FeatureDigitSeparator = MessageBase + 12707,
IDS_FeatureLocalFunctions = MessageBase + 12708,
IDS_FeatureNullableReferenceTypes = MessageBase + 12709,
IDS_FeatureRefLocalsReturns = MessageBase + 12710,
IDS_FeatureTuples = MessageBase + 12711,
IDS_FeatureOutVar = MessageBase + 12713,
// IDS_FeaturePragmaWarningEnable = MessageBase + 12714,
IDS_FeatureExpressionBodiedAccessor = MessageBase + 12715,
IDS_FeatureExpressionBodiedDeOrConstructor = MessageBase + 12716,
IDS_ThrowExpression = MessageBase + 12717,
IDS_FeatureDefaultLiteral = MessageBase + 12718,
IDS_FeatureInferredTupleNames = MessageBase + 12719,
IDS_FeatureGenericPatternMatching = MessageBase + 12720,
IDS_FeatureAsyncMain = MessageBase + 12721,
IDS_LangVersions = MessageBase + 12722,
IDS_FeatureLeadingDigitSeparator = MessageBase + 12723,
IDS_FeatureNonTrailingNamedArguments = MessageBase + 12724,
IDS_FeatureReadOnlyReferences = MessageBase + 12725,
IDS_FeatureRefStructs = MessageBase + 12726,
IDS_FeatureReadOnlyStructs = MessageBase + 12727,
IDS_FeatureRefExtensionMethods = MessageBase + 12728,
// IDS_StackAllocExpression = MessageBase + 12729,
IDS_FeaturePrivateProtected = MessageBase + 12730,
IDS_FeatureRefConditional = MessageBase + 12731,
IDS_FeatureAttributesOnBackingFields = MessageBase + 12732,
IDS_FeatureImprovedOverloadCandidates = MessageBase + 12733,
IDS_FeatureRefReassignment = MessageBase + 12734,
IDS_FeatureRefFor = MessageBase + 12735,
IDS_FeatureRefForEach = MessageBase + 12736,
IDS_FeatureEnumGenericTypeConstraint = MessageBase + 12737,
IDS_FeatureDelegateGenericTypeConstraint = MessageBase + 12738,
IDS_FeatureUnmanagedGenericTypeConstraint = MessageBase + 12739,
IDS_FeatureStackAllocInitializer = MessageBase + 12740,
IDS_FeatureTupleEquality = MessageBase + 12741,
IDS_FeatureExpressionVariablesInQueriesAndInitializers = MessageBase + 12742,
IDS_FeatureExtensibleFixedStatement = MessageBase + 12743,
IDS_FeatureIndexingMovableFixedBuffers = MessageBase + 12744,
IDS_FeatureAltInterpolatedVerbatimStrings = MessageBase + 12745,
IDS_FeatureCoalesceAssignmentExpression = MessageBase + 12746,
IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator = MessageBase + 12747,
IDS_FeatureNotNullGenericTypeConstraint = MessageBase + 12748,
IDS_FeatureIndexOperator = MessageBase + 12749,
IDS_FeatureRangeOperator = MessageBase + 12750,
IDS_FeatureAsyncStreams = MessageBase + 12751,
IDS_FeatureRecursivePatterns = MessageBase + 12752,
IDS_Disposable = MessageBase + 12753,
IDS_FeatureUsingDeclarations = MessageBase + 12754,
IDS_FeatureStaticLocalFunctions = MessageBase + 12755,
IDS_FeatureNameShadowingInNestedFunctions = MessageBase + 12756,
IDS_FeatureUnmanagedConstructedTypes = MessageBase + 12757,
IDS_FeatureObsoleteOnPropertyAccessor = MessageBase + 12758,
IDS_FeatureReadOnlyMembers = MessageBase + 12759,
IDS_DefaultInterfaceImplementation = MessageBase + 12760,
IDS_OverrideWithConstraints = MessageBase + 12761,
IDS_FeatureNestedStackalloc = MessageBase + 12762,
IDS_FeatureSwitchExpression = MessageBase + 12763,
IDS_FeatureAsyncUsing = MessageBase + 12764,
IDS_FeatureLambdaDiscardParameters = MessageBase + 12765,
IDS_FeatureLocalFunctionAttributes = MessageBase + 12766,
IDS_FeatureExternLocalFunctions = MessageBase + 12767,
IDS_FeatureMemberNotNull = MessageBase + 12768,
IDS_FeatureNativeInt = MessageBase + 12769,
IDS_FeatureImplicitObjectCreation = MessageBase + 12770,
IDS_FeatureTypePattern = MessageBase + 12771,
IDS_FeatureParenthesizedPattern = MessageBase + 12772,
IDS_FeatureOrPattern = MessageBase + 12773,
IDS_FeatureAndPattern = MessageBase + 12774,
IDS_FeatureNotPattern = MessageBase + 12775,
IDS_FeatureRelationalPattern = MessageBase + 12776,
IDS_FeatureExtendedPartialMethods = MessageBase + 12777,
IDS_TopLevelStatements = MessageBase + 12778,
IDS_FeatureFunctionPointers = MessageBase + 12779,
IDS_AddressOfMethodGroup = MessageBase + 12780,
IDS_FeatureInitOnlySetters = MessageBase + 12781,
IDS_FeatureRecords = MessageBase + 12782,
IDS_FeatureNullPointerConstantPattern = MessageBase + 12783,
IDS_FeatureModuleInitializers = MessageBase + 12784,
IDS_FeatureTargetTypedConditional = MessageBase + 12785,
IDS_FeatureCovariantReturnsForOverrides = MessageBase + 12786,
IDS_FeatureExtensionGetEnumerator = MessageBase + 12787,
IDS_FeatureExtensionGetAsyncEnumerator = MessageBase + 12788,
IDS_Parameter = MessageBase + 12789,
IDS_Return = MessageBase + 12790,
IDS_FeatureVarianceSafetyForStaticInterfaceMembers = MessageBase + 12791,
IDS_FeatureConstantInterpolatedStrings = MessageBase + 12792,
IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction = MessageBase + 12793,
IDS_FeatureSealedToStringInRecord = MessageBase + 12794,
IDS_FeatureRecordStructs = MessageBase + 12795,
IDS_FeatureWithOnStructs = MessageBase + 12796,
IDS_FeaturePositionalFieldsInRecords = MessageBase + 12797,
IDS_FeatureGlobalUsing = MessageBase + 12798,
IDS_FeatureInferredDelegateType = MessageBase + 12799,
IDS_FeatureLambdaAttributes = MessageBase + 12800,
IDS_FeatureWithOnAnonymousTypes = MessageBase + 12801,
IDS_FeatureExtendedPropertyPatterns = MessageBase + 12802,
IDS_FeatureStaticAbstractMembersInInterfaces = MessageBase + 12803,
IDS_FeatureLambdaReturnType = MessageBase + 12804,
IDS_AsyncMethodBuilderOverride = MessageBase + 12805,
IDS_FeatureImplicitImplementationOfNonPublicMembers = MessageBase + 12806,
IDS_FeatureLineSpanDirective = MessageBase + 12807,
IDS_FeatureImprovedInterpolatedStrings = MessageBase + 12808,
IDS_FeatureFileScopedNamespace = MessageBase + 12809,
IDS_FeatureParameterlessStructConstructors = MessageBase + 12810,
IDS_FeatureStructFieldInitializers = MessageBase + 12811,
IDS_FeatureGenericAttributes = MessageBase + 12812,
}
// Message IDs may refer to strings that need to be localized.
// This struct makes an IFormattable wrapper around a MessageID
internal struct LocalizableErrorArgument : IFormattable
{
private readonly MessageID _id;
internal LocalizableErrorArgument(MessageID id)
{
_id = id;
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
return ErrorFacts.GetMessage(_id, formatProvider as System.Globalization.CultureInfo);
}
}
// And this extension method makes it easy to localize MessageIDs:
internal static partial class MessageIDExtensions
{
public static LocalizableErrorArgument Localize(this MessageID id)
{
return new LocalizableErrorArgument(id);
}
// Returns the string to be used in the /features flag switch to enable the MessageID feature.
// Always call this before RequiredVersion:
// If this method returns null, call RequiredVersion and use that.
// If this method returns non-null, use that.
// Features should be mutually exclusive between RequiredFeature and RequiredVersion.
// (hence the above rule - RequiredVersion throws when RequiredFeature returns non-null)
internal static string? RequiredFeature(this MessageID feature)
{
// Check for current experimental features, if any, in the current branch.
switch (feature)
{
default:
return null;
}
}
internal static bool CheckFeatureAvailability(
this MessageID feature,
BindingDiagnosticBag diagnostics,
SyntaxNode syntax,
Location? location = null)
{
var diag = GetFeatureAvailabilityDiagnosticInfo(feature, (CSharpParseOptions)syntax.SyntaxTree.Options);
if (diag is object)
{
diagnostics.Add(diag, location ?? syntax.GetLocation());
return false;
}
return true;
}
internal static bool CheckFeatureAvailability(
this MessageID feature,
BindingDiagnosticBag diagnostics,
Compilation compilation,
Location location)
{
if (GetFeatureAvailabilityDiagnosticInfo(feature, (CSharpCompilation)compilation) is { } diagInfo)
{
diagnostics.Add(diagInfo, location);
return false;
}
return true;
}
internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpParseOptions options)
=> options.IsFeatureEnabled(feature) ? null : GetDisabledFeatureDiagnosticInfo(feature, options.LanguageVersion);
internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpCompilation compilation)
=> compilation.IsFeatureEnabled(feature) ? null : GetDisabledFeatureDiagnosticInfo(feature, compilation.LanguageVersion);
private static CSDiagnosticInfo GetDisabledFeatureDiagnosticInfo(MessageID feature, LanguageVersion availableVersion)
{
string? requiredFeature = feature.RequiredFeature();
if (requiredFeature != null)
{
return new CSDiagnosticInfo(ErrorCode.ERR_FeatureIsExperimental, feature.Localize(), requiredFeature);
}
LanguageVersion requiredVersion = feature.RequiredVersion();
return requiredVersion == LanguageVersion.Preview.MapSpecifiedToEffectiveVersion()
? new CSDiagnosticInfo(ErrorCode.ERR_FeatureInPreview, feature.Localize())
: new CSDiagnosticInfo(availableVersion.GetErrorCode(), feature.Localize(), new CSharpRequiredLanguageVersion(requiredVersion));
}
internal static LanguageVersion RequiredVersion(this MessageID feature)
{
Debug.Assert(RequiredFeature(feature) == null);
// Based on CSourceParser::GetFeatureUsage from SourceParser.cpp.
// Checks are in the LanguageParser unless otherwise noted.
switch (feature)
{
// C# preview features.
case MessageID.IDS_FeatureStaticAbstractMembersInInterfaces: // semantic check
case MessageID.IDS_FeatureGenericAttributes: // semantic check
return LanguageVersion.Preview;
// C# 10.0 features.
case MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction: // semantic check
case MessageID.IDS_FeatureSealedToStringInRecord: // semantic check
case MessageID.IDS_FeatureImprovedInterpolatedStrings: // semantic check
case MessageID.IDS_FeatureRecordStructs:
case MessageID.IDS_FeatureWithOnStructs: // semantic check
case MessageID.IDS_FeatureWithOnAnonymousTypes: // semantic check
case MessageID.IDS_FeaturePositionalFieldsInRecords: // semantic check
case MessageID.IDS_FeatureGlobalUsing:
case MessageID.IDS_FeatureInferredDelegateType: // semantic check
case MessageID.IDS_FeatureLambdaAttributes: // semantic check
case MessageID.IDS_FeatureExtendedPropertyPatterns:
case MessageID.IDS_FeatureLambdaReturnType: // semantic check
case MessageID.IDS_AsyncMethodBuilderOverride: // semantic check
case MessageID.IDS_FeatureConstantInterpolatedStrings: // semantic check
case MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers: // semantic check
case MessageID.IDS_FeatureLineSpanDirective:
case MessageID.IDS_FeatureFileScopedNamespace: // syntax check
case MessageID.IDS_FeatureParameterlessStructConstructors: // semantic check
case MessageID.IDS_FeatureStructFieldInitializers: // semantic check
return LanguageVersion.CSharp10;
// C# 9.0 features.
case MessageID.IDS_FeatureLambdaDiscardParameters: // semantic check
case MessageID.IDS_FeatureFunctionPointers:
case MessageID.IDS_FeatureLocalFunctionAttributes: // syntax check
case MessageID.IDS_FeatureExternLocalFunctions: // syntax check
case MessageID.IDS_FeatureImplicitObjectCreation: // syntax check
case MessageID.IDS_FeatureMemberNotNull:
case MessageID.IDS_FeatureAndPattern:
case MessageID.IDS_FeatureNotPattern:
case MessageID.IDS_FeatureOrPattern:
case MessageID.IDS_FeatureParenthesizedPattern:
case MessageID.IDS_FeatureTypePattern:
case MessageID.IDS_FeatureRelationalPattern:
case MessageID.IDS_FeatureExtensionGetEnumerator: // semantic check
case MessageID.IDS_FeatureExtensionGetAsyncEnumerator: // semantic check
case MessageID.IDS_FeatureNativeInt:
case MessageID.IDS_FeatureExtendedPartialMethods: // semantic check
case MessageID.IDS_TopLevelStatements:
case MessageID.IDS_FeatureInitOnlySetters: // semantic check
case MessageID.IDS_FeatureRecords:
case MessageID.IDS_FeatureTargetTypedConditional: // semantic check
case MessageID.IDS_FeatureCovariantReturnsForOverrides: // semantic check
case MessageID.IDS_FeatureStaticAnonymousFunction: // syntax check
case MessageID.IDS_FeatureModuleInitializers: // semantic check on method attribute
case MessageID.IDS_FeatureDefaultTypeParameterConstraint:
case MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers: // semantic check
return LanguageVersion.CSharp9;
// C# 8.0 features.
case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:
case MessageID.IDS_FeatureCoalesceAssignmentExpression:
case MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator:
case MessageID.IDS_FeatureNullableReferenceTypes: // syntax and semantic check
case MessageID.IDS_FeatureIndexOperator: // semantic check
case MessageID.IDS_FeatureRangeOperator: // semantic check
case MessageID.IDS_FeatureAsyncStreams:
case MessageID.IDS_FeatureRecursivePatterns:
case MessageID.IDS_FeatureUsingDeclarations:
case MessageID.IDS_FeatureStaticLocalFunctions:
case MessageID.IDS_FeatureNameShadowingInNestedFunctions:
case MessageID.IDS_FeatureUnmanagedConstructedTypes: // semantic check
case MessageID.IDS_FeatureObsoleteOnPropertyAccessor:
case MessageID.IDS_FeatureReadOnlyMembers:
case MessageID.IDS_DefaultInterfaceImplementation: // semantic check
case MessageID.IDS_OverrideWithConstraints: // semantic check
case MessageID.IDS_FeatureNestedStackalloc: // semantic check
case MessageID.IDS_FeatureNotNullGenericTypeConstraint:// semantic check
case MessageID.IDS_FeatureSwitchExpression:
case MessageID.IDS_FeatureAsyncUsing:
case MessageID.IDS_FeatureNullPointerConstantPattern: //semantic check
return LanguageVersion.CSharp8;
// C# 7.3 features.
case MessageID.IDS_FeatureAttributesOnBackingFields: // semantic check
case MessageID.IDS_FeatureImprovedOverloadCandidates: // semantic check
case MessageID.IDS_FeatureTupleEquality: // semantic check
case MessageID.IDS_FeatureRefReassignment:
case MessageID.IDS_FeatureRefFor:
case MessageID.IDS_FeatureRefForEach:
case MessageID.IDS_FeatureEnumGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureDelegateGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureUnmanagedGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureStackAllocInitializer:
case MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers: // semantic check
case MessageID.IDS_FeatureExtensibleFixedStatement: // semantic check
case MessageID.IDS_FeatureIndexingMovableFixedBuffers: //semantic check
return LanguageVersion.CSharp7_3;
// C# 7.2 features.
case MessageID.IDS_FeatureNonTrailingNamedArguments: // semantic check
case MessageID.IDS_FeatureLeadingDigitSeparator:
case MessageID.IDS_FeaturePrivateProtected:
case MessageID.IDS_FeatureReadOnlyReferences:
case MessageID.IDS_FeatureRefStructs:
case MessageID.IDS_FeatureReadOnlyStructs:
case MessageID.IDS_FeatureRefExtensionMethods:
case MessageID.IDS_FeatureRefConditional:
return LanguageVersion.CSharp7_2;
// C# 7.1 features.
case MessageID.IDS_FeatureAsyncMain:
case MessageID.IDS_FeatureDefaultLiteral:
case MessageID.IDS_FeatureInferredTupleNames:
case MessageID.IDS_FeatureGenericPatternMatching:
return LanguageVersion.CSharp7_1;
// C# 7 features.
case MessageID.IDS_FeatureBinaryLiteral:
case MessageID.IDS_FeatureDigitSeparator:
case MessageID.IDS_FeatureLocalFunctions:
case MessageID.IDS_FeatureRefLocalsReturns:
case MessageID.IDS_FeaturePatternMatching:
case MessageID.IDS_FeatureThrowExpression:
case MessageID.IDS_FeatureTuples:
case MessageID.IDS_FeatureOutVar:
case MessageID.IDS_FeatureExpressionBodiedAccessor:
case MessageID.IDS_FeatureExpressionBodiedDeOrConstructor:
case MessageID.IDS_FeatureDiscards:
return LanguageVersion.CSharp7;
// C# 6 features.
case MessageID.IDS_FeatureExceptionFilter:
case MessageID.IDS_FeatureAutoPropertyInitializer:
case MessageID.IDS_FeatureNullPropagatingOperator:
case MessageID.IDS_FeatureExpressionBodiedMethod:
case MessageID.IDS_FeatureExpressionBodiedProperty:
case MessageID.IDS_FeatureExpressionBodiedIndexer:
case MessageID.IDS_FeatureNameof:
case MessageID.IDS_FeatureDictionaryInitializer:
case MessageID.IDS_FeatureUsingStatic:
case MessageID.IDS_FeatureInterpolatedStrings:
case MessageID.IDS_AwaitInCatchAndFinally:
case MessageID.IDS_FeatureReadonlyAutoImplementedProperties:
return LanguageVersion.CSharp6;
// C# 5 features.
case MessageID.IDS_FeatureAsync:
return LanguageVersion.CSharp5;
// C# 4 features.
case MessageID.IDS_FeatureDynamic: // Checked in the binder.
case MessageID.IDS_FeatureTypeVariance:
case MessageID.IDS_FeatureNamedArgument:
case MessageID.IDS_FeatureOptionalParameter:
return LanguageVersion.CSharp4;
// C# 3 features.
case MessageID.IDS_FeatureImplicitArray:
case MessageID.IDS_FeatureAnonymousTypes:
case MessageID.IDS_FeatureObjectInitializer:
case MessageID.IDS_FeatureCollectionInitializer:
case MessageID.IDS_FeatureLambda:
case MessageID.IDS_FeatureQueryExpression:
case MessageID.IDS_FeatureExtensionMethod:
case MessageID.IDS_FeaturePartialMethod:
case MessageID.IDS_FeatureImplicitLocal: // Checked in the binder.
case MessageID.IDS_FeatureAutoImplementedProperties:
return LanguageVersion.CSharp3;
// C# 2 features.
case MessageID.IDS_FeatureGenerics: // Also affects crefs.
case MessageID.IDS_FeatureAnonDelegates:
case MessageID.IDS_FeatureGlobalNamespace: // Also affects crefs.
case MessageID.IDS_FeatureFixedBuffer:
case MessageID.IDS_FeatureStaticClasses:
case MessageID.IDS_FeaturePartialTypes:
case MessageID.IDS_FeaturePropertyAccessorMods:
case MessageID.IDS_FeatureExternAlias:
case MessageID.IDS_FeatureIterators:
case MessageID.IDS_FeatureDefault:
case MessageID.IDS_FeatureNullable:
case MessageID.IDS_FeaturePragma: // Checked in the directive parser.
case MessageID.IDS_FeatureSwitchOnBool: // Checked in the binder.
return LanguageVersion.CSharp2;
// Special C# 2 feature: only a warning in C# 1.
case MessageID.IDS_FeatureModuleAttrLoc:
return LanguageVersion.CSharp1;
default:
throw ExceptionUtilities.UnexpectedValue(feature);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum MessageID
{
None = 0,
MessageBase = 1200,
IDS_SK_METHOD = MessageBase + 2000,
IDS_SK_TYPE = MessageBase + 2001,
IDS_SK_NAMESPACE = MessageBase + 2002,
IDS_SK_FIELD = MessageBase + 2003,
IDS_SK_PROPERTY = MessageBase + 2004,
IDS_SK_UNKNOWN = MessageBase + 2005,
IDS_SK_VARIABLE = MessageBase + 2006,
IDS_SK_EVENT = MessageBase + 2007,
IDS_SK_TYVAR = MessageBase + 2008,
//IDS_SK_GCLASS = MessageBase + 2009,
IDS_SK_ALIAS = MessageBase + 2010,
//IDS_SK_EXTERNALIAS = MessageBase + 2011,
IDS_SK_LABEL = MessageBase + 2012,
IDS_SK_CONSTRUCTOR = MessageBase + 2013,
IDS_NULL = MessageBase + 10001,
//IDS_RELATEDERROR = MessageBase + 10002,
//IDS_RELATEDWARNING = MessageBase + 10003,
IDS_XMLIGNORED = MessageBase + 10004,
IDS_XMLIGNORED2 = MessageBase + 10005,
IDS_XMLFAILEDINCLUDE = MessageBase + 10006,
IDS_XMLBADINCLUDE = MessageBase + 10007,
IDS_XMLNOINCLUDE = MessageBase + 10008,
IDS_XMLMISSINGINCLUDEFILE = MessageBase + 10009,
IDS_XMLMISSINGINCLUDEPATH = MessageBase + 10010,
IDS_GlobalNamespace = MessageBase + 10011,
IDS_FeatureGenerics = MessageBase + 12500,
IDS_FeatureAnonDelegates = MessageBase + 12501,
IDS_FeatureModuleAttrLoc = MessageBase + 12502,
IDS_FeatureGlobalNamespace = MessageBase + 12503,
IDS_FeatureFixedBuffer = MessageBase + 12504,
IDS_FeaturePragma = MessageBase + 12505,
IDS_FOREACHLOCAL = MessageBase + 12506,
IDS_USINGLOCAL = MessageBase + 12507,
IDS_FIXEDLOCAL = MessageBase + 12508,
IDS_FeatureStaticClasses = MessageBase + 12511,
IDS_FeaturePartialTypes = MessageBase + 12512,
IDS_MethodGroup = MessageBase + 12513,
IDS_AnonMethod = MessageBase + 12514,
IDS_FeatureSwitchOnBool = MessageBase + 12517,
//IDS_WarnAsError = MessageBase + 12518,
IDS_Collection = MessageBase + 12520,
IDS_FeaturePropertyAccessorMods = MessageBase + 12522,
IDS_FeatureExternAlias = MessageBase + 12523,
IDS_FeatureIterators = MessageBase + 12524,
IDS_FeatureDefault = MessageBase + 12525,
IDS_FeatureNullable = MessageBase + 12528,
IDS_Lambda = MessageBase + 12531,
IDS_FeaturePatternMatching = MessageBase + 12532,
IDS_FeatureThrowExpression = MessageBase + 12533,
IDS_FeatureImplicitArray = MessageBase + 12557,
IDS_FeatureImplicitLocal = MessageBase + 12558,
IDS_FeatureAnonymousTypes = MessageBase + 12559,
IDS_FeatureAutoImplementedProperties = MessageBase + 12560,
IDS_FeatureObjectInitializer = MessageBase + 12561,
IDS_FeatureCollectionInitializer = MessageBase + 12562,
IDS_FeatureLambda = MessageBase + 12563,
IDS_FeatureQueryExpression = MessageBase + 12564,
IDS_FeatureExtensionMethod = MessageBase + 12565,
IDS_FeaturePartialMethod = MessageBase + 12566,
IDS_FeatureDynamic = MessageBase + 12644,
IDS_FeatureTypeVariance = MessageBase + 12645,
IDS_FeatureNamedArgument = MessageBase + 12646,
IDS_FeatureOptionalParameter = MessageBase + 12647,
IDS_FeatureExceptionFilter = MessageBase + 12648,
IDS_FeatureAutoPropertyInitializer = MessageBase + 12649,
IDS_SK_TYPE_OR_NAMESPACE = MessageBase + 12652,
IDS_Contravariant = MessageBase + 12659,
IDS_Contravariantly = MessageBase + 12660,
IDS_Covariant = MessageBase + 12661,
IDS_Covariantly = MessageBase + 12662,
IDS_Invariantly = MessageBase + 12663,
IDS_FeatureAsync = MessageBase + 12668,
IDS_FeatureStaticAnonymousFunction = MessageBase + 12669,
IDS_LIB_ENV = MessageBase + 12680,
IDS_LIB_OPTION = MessageBase + 12681,
IDS_REFERENCEPATH_OPTION = MessageBase + 12682,
IDS_DirectoryDoesNotExist = MessageBase + 12683,
IDS_DirectoryHasInvalidPath = MessageBase + 12684,
IDS_Namespace1 = MessageBase + 12685,
IDS_PathList = MessageBase + 12686,
IDS_Text = MessageBase + 12687,
IDS_FeatureDiscards = MessageBase + 12688,
IDS_FeatureDefaultTypeParameterConstraint = MessageBase + 12689,
IDS_FeatureNullPropagatingOperator = MessageBase + 12690,
IDS_FeatureExpressionBodiedMethod = MessageBase + 12691,
IDS_FeatureExpressionBodiedProperty = MessageBase + 12692,
IDS_FeatureExpressionBodiedIndexer = MessageBase + 12693,
// IDS_VersionExperimental = MessageBase + 12694,
IDS_FeatureNameof = MessageBase + 12695,
IDS_FeatureDictionaryInitializer = MessageBase + 12696,
IDS_ToolName = MessageBase + 12697,
IDS_LogoLine1 = MessageBase + 12698,
IDS_LogoLine2 = MessageBase + 12699,
IDS_CSCHelp = MessageBase + 12700,
IDS_FeatureUsingStatic = MessageBase + 12701,
IDS_FeatureInterpolatedStrings = MessageBase + 12702,
IDS_OperationCausedStackOverflow = MessageBase + 12703,
IDS_AwaitInCatchAndFinally = MessageBase + 12704,
IDS_FeatureReadonlyAutoImplementedProperties = MessageBase + 12705,
IDS_FeatureBinaryLiteral = MessageBase + 12706,
IDS_FeatureDigitSeparator = MessageBase + 12707,
IDS_FeatureLocalFunctions = MessageBase + 12708,
IDS_FeatureNullableReferenceTypes = MessageBase + 12709,
IDS_FeatureRefLocalsReturns = MessageBase + 12710,
IDS_FeatureTuples = MessageBase + 12711,
IDS_FeatureOutVar = MessageBase + 12713,
// IDS_FeaturePragmaWarningEnable = MessageBase + 12714,
IDS_FeatureExpressionBodiedAccessor = MessageBase + 12715,
IDS_FeatureExpressionBodiedDeOrConstructor = MessageBase + 12716,
IDS_ThrowExpression = MessageBase + 12717,
IDS_FeatureDefaultLiteral = MessageBase + 12718,
IDS_FeatureInferredTupleNames = MessageBase + 12719,
IDS_FeatureGenericPatternMatching = MessageBase + 12720,
IDS_FeatureAsyncMain = MessageBase + 12721,
IDS_LangVersions = MessageBase + 12722,
IDS_FeatureLeadingDigitSeparator = MessageBase + 12723,
IDS_FeatureNonTrailingNamedArguments = MessageBase + 12724,
IDS_FeatureReadOnlyReferences = MessageBase + 12725,
IDS_FeatureRefStructs = MessageBase + 12726,
IDS_FeatureReadOnlyStructs = MessageBase + 12727,
IDS_FeatureRefExtensionMethods = MessageBase + 12728,
// IDS_StackAllocExpression = MessageBase + 12729,
IDS_FeaturePrivateProtected = MessageBase + 12730,
IDS_FeatureRefConditional = MessageBase + 12731,
IDS_FeatureAttributesOnBackingFields = MessageBase + 12732,
IDS_FeatureImprovedOverloadCandidates = MessageBase + 12733,
IDS_FeatureRefReassignment = MessageBase + 12734,
IDS_FeatureRefFor = MessageBase + 12735,
IDS_FeatureRefForEach = MessageBase + 12736,
IDS_FeatureEnumGenericTypeConstraint = MessageBase + 12737,
IDS_FeatureDelegateGenericTypeConstraint = MessageBase + 12738,
IDS_FeatureUnmanagedGenericTypeConstraint = MessageBase + 12739,
IDS_FeatureStackAllocInitializer = MessageBase + 12740,
IDS_FeatureTupleEquality = MessageBase + 12741,
IDS_FeatureExpressionVariablesInQueriesAndInitializers = MessageBase + 12742,
IDS_FeatureExtensibleFixedStatement = MessageBase + 12743,
IDS_FeatureIndexingMovableFixedBuffers = MessageBase + 12744,
IDS_FeatureAltInterpolatedVerbatimStrings = MessageBase + 12745,
IDS_FeatureCoalesceAssignmentExpression = MessageBase + 12746,
IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator = MessageBase + 12747,
IDS_FeatureNotNullGenericTypeConstraint = MessageBase + 12748,
IDS_FeatureIndexOperator = MessageBase + 12749,
IDS_FeatureRangeOperator = MessageBase + 12750,
IDS_FeatureAsyncStreams = MessageBase + 12751,
IDS_FeatureRecursivePatterns = MessageBase + 12752,
IDS_Disposable = MessageBase + 12753,
IDS_FeatureUsingDeclarations = MessageBase + 12754,
IDS_FeatureStaticLocalFunctions = MessageBase + 12755,
IDS_FeatureNameShadowingInNestedFunctions = MessageBase + 12756,
IDS_FeatureUnmanagedConstructedTypes = MessageBase + 12757,
IDS_FeatureObsoleteOnPropertyAccessor = MessageBase + 12758,
IDS_FeatureReadOnlyMembers = MessageBase + 12759,
IDS_DefaultInterfaceImplementation = MessageBase + 12760,
IDS_OverrideWithConstraints = MessageBase + 12761,
IDS_FeatureNestedStackalloc = MessageBase + 12762,
IDS_FeatureSwitchExpression = MessageBase + 12763,
IDS_FeatureAsyncUsing = MessageBase + 12764,
IDS_FeatureLambdaDiscardParameters = MessageBase + 12765,
IDS_FeatureLocalFunctionAttributes = MessageBase + 12766,
IDS_FeatureExternLocalFunctions = MessageBase + 12767,
IDS_FeatureMemberNotNull = MessageBase + 12768,
IDS_FeatureNativeInt = MessageBase + 12769,
IDS_FeatureImplicitObjectCreation = MessageBase + 12770,
IDS_FeatureTypePattern = MessageBase + 12771,
IDS_FeatureParenthesizedPattern = MessageBase + 12772,
IDS_FeatureOrPattern = MessageBase + 12773,
IDS_FeatureAndPattern = MessageBase + 12774,
IDS_FeatureNotPattern = MessageBase + 12775,
IDS_FeatureRelationalPattern = MessageBase + 12776,
IDS_FeatureExtendedPartialMethods = MessageBase + 12777,
IDS_TopLevelStatements = MessageBase + 12778,
IDS_FeatureFunctionPointers = MessageBase + 12779,
IDS_AddressOfMethodGroup = MessageBase + 12780,
IDS_FeatureInitOnlySetters = MessageBase + 12781,
IDS_FeatureRecords = MessageBase + 12782,
IDS_FeatureNullPointerConstantPattern = MessageBase + 12783,
IDS_FeatureModuleInitializers = MessageBase + 12784,
IDS_FeatureTargetTypedConditional = MessageBase + 12785,
IDS_FeatureCovariantReturnsForOverrides = MessageBase + 12786,
IDS_FeatureExtensionGetEnumerator = MessageBase + 12787,
IDS_FeatureExtensionGetAsyncEnumerator = MessageBase + 12788,
IDS_Parameter = MessageBase + 12789,
IDS_Return = MessageBase + 12790,
IDS_FeatureVarianceSafetyForStaticInterfaceMembers = MessageBase + 12791,
IDS_FeatureConstantInterpolatedStrings = MessageBase + 12792,
IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction = MessageBase + 12793,
IDS_FeatureSealedToStringInRecord = MessageBase + 12794,
IDS_FeatureRecordStructs = MessageBase + 12795,
IDS_FeatureWithOnStructs = MessageBase + 12796,
IDS_FeaturePositionalFieldsInRecords = MessageBase + 12797,
IDS_FeatureGlobalUsing = MessageBase + 12798,
IDS_FeatureInferredDelegateType = MessageBase + 12799,
IDS_FeatureLambdaAttributes = MessageBase + 12800,
IDS_FeatureWithOnAnonymousTypes = MessageBase + 12801,
IDS_FeatureExtendedPropertyPatterns = MessageBase + 12802,
IDS_FeatureStaticAbstractMembersInInterfaces = MessageBase + 12803,
IDS_FeatureLambdaReturnType = MessageBase + 12804,
IDS_AsyncMethodBuilderOverride = MessageBase + 12805,
IDS_FeatureImplicitImplementationOfNonPublicMembers = MessageBase + 12806,
IDS_FeatureLineSpanDirective = MessageBase + 12807,
IDS_FeatureImprovedInterpolatedStrings = MessageBase + 12808,
IDS_FeatureFileScopedNamespace = MessageBase + 12809,
IDS_FeatureParameterlessStructConstructors = MessageBase + 12810,
IDS_FeatureStructFieldInitializers = MessageBase + 12811,
IDS_FeatureGenericAttributes = MessageBase + 12812,
}
// Message IDs may refer to strings that need to be localized.
// This struct makes an IFormattable wrapper around a MessageID
internal struct LocalizableErrorArgument : IFormattable
{
private readonly MessageID _id;
internal LocalizableErrorArgument(MessageID id)
{
_id = id;
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
return ErrorFacts.GetMessage(_id, formatProvider as System.Globalization.CultureInfo);
}
}
// And this extension method makes it easy to localize MessageIDs:
internal static partial class MessageIDExtensions
{
public static LocalizableErrorArgument Localize(this MessageID id)
{
return new LocalizableErrorArgument(id);
}
// Returns the string to be used in the /features flag switch to enable the MessageID feature.
// Always call this before RequiredVersion:
// If this method returns null, call RequiredVersion and use that.
// If this method returns non-null, use that.
// Features should be mutually exclusive between RequiredFeature and RequiredVersion.
// (hence the above rule - RequiredVersion throws when RequiredFeature returns non-null)
internal static string? RequiredFeature(this MessageID feature)
{
// Check for current experimental features, if any, in the current branch.
switch (feature)
{
default:
return null;
}
}
internal static bool CheckFeatureAvailability(
this MessageID feature,
BindingDiagnosticBag diagnostics,
SyntaxNode syntax,
Location? location = null)
{
var diag = GetFeatureAvailabilityDiagnosticInfo(feature, (CSharpParseOptions)syntax.SyntaxTree.Options);
if (diag is object)
{
diagnostics.Add(diag, location ?? syntax.GetLocation());
return false;
}
return true;
}
internal static bool CheckFeatureAvailability(
this MessageID feature,
BindingDiagnosticBag diagnostics,
Compilation compilation,
Location location)
{
if (GetFeatureAvailabilityDiagnosticInfo(feature, (CSharpCompilation)compilation) is { } diagInfo)
{
diagnostics.Add(diagInfo, location);
return false;
}
return true;
}
internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpParseOptions options)
=> options.IsFeatureEnabled(feature) ? null : GetDisabledFeatureDiagnosticInfo(feature, options.LanguageVersion);
internal static CSDiagnosticInfo? GetFeatureAvailabilityDiagnosticInfo(this MessageID feature, CSharpCompilation compilation)
=> compilation.IsFeatureEnabled(feature) ? null : GetDisabledFeatureDiagnosticInfo(feature, compilation.LanguageVersion);
private static CSDiagnosticInfo GetDisabledFeatureDiagnosticInfo(MessageID feature, LanguageVersion availableVersion)
{
string? requiredFeature = feature.RequiredFeature();
if (requiredFeature != null)
{
return new CSDiagnosticInfo(ErrorCode.ERR_FeatureIsExperimental, feature.Localize(), requiredFeature);
}
LanguageVersion requiredVersion = feature.RequiredVersion();
return requiredVersion == LanguageVersion.Preview.MapSpecifiedToEffectiveVersion()
? new CSDiagnosticInfo(ErrorCode.ERR_FeatureInPreview, feature.Localize())
: new CSDiagnosticInfo(availableVersion.GetErrorCode(), feature.Localize(), new CSharpRequiredLanguageVersion(requiredVersion));
}
internal static LanguageVersion RequiredVersion(this MessageID feature)
{
Debug.Assert(RequiredFeature(feature) == null);
// Based on CSourceParser::GetFeatureUsage from SourceParser.cpp.
// Checks are in the LanguageParser unless otherwise noted.
switch (feature)
{
// C# preview features.
case MessageID.IDS_FeatureStaticAbstractMembersInInterfaces: // semantic check
case MessageID.IDS_FeatureGenericAttributes: // semantic check
return LanguageVersion.Preview;
// C# 10.0 features.
case MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction: // semantic check
case MessageID.IDS_FeatureSealedToStringInRecord: // semantic check
case MessageID.IDS_FeatureImprovedInterpolatedStrings: // semantic check
case MessageID.IDS_FeatureRecordStructs:
case MessageID.IDS_FeatureWithOnStructs: // semantic check
case MessageID.IDS_FeatureWithOnAnonymousTypes: // semantic check
case MessageID.IDS_FeaturePositionalFieldsInRecords: // semantic check
case MessageID.IDS_FeatureGlobalUsing:
case MessageID.IDS_FeatureInferredDelegateType: // semantic check
case MessageID.IDS_FeatureLambdaAttributes: // semantic check
case MessageID.IDS_FeatureExtendedPropertyPatterns:
case MessageID.IDS_FeatureLambdaReturnType: // semantic check
case MessageID.IDS_AsyncMethodBuilderOverride: // semantic check
case MessageID.IDS_FeatureConstantInterpolatedStrings: // semantic check
case MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers: // semantic check
case MessageID.IDS_FeatureLineSpanDirective:
case MessageID.IDS_FeatureFileScopedNamespace: // syntax check
case MessageID.IDS_FeatureParameterlessStructConstructors: // semantic check
case MessageID.IDS_FeatureStructFieldInitializers: // semantic check
return LanguageVersion.CSharp10;
// C# 9.0 features.
case MessageID.IDS_FeatureLambdaDiscardParameters: // semantic check
case MessageID.IDS_FeatureFunctionPointers:
case MessageID.IDS_FeatureLocalFunctionAttributes: // syntax check
case MessageID.IDS_FeatureExternLocalFunctions: // syntax check
case MessageID.IDS_FeatureImplicitObjectCreation: // syntax check
case MessageID.IDS_FeatureMemberNotNull:
case MessageID.IDS_FeatureAndPattern:
case MessageID.IDS_FeatureNotPattern:
case MessageID.IDS_FeatureOrPattern:
case MessageID.IDS_FeatureParenthesizedPattern:
case MessageID.IDS_FeatureTypePattern:
case MessageID.IDS_FeatureRelationalPattern:
case MessageID.IDS_FeatureExtensionGetEnumerator: // semantic check
case MessageID.IDS_FeatureExtensionGetAsyncEnumerator: // semantic check
case MessageID.IDS_FeatureNativeInt:
case MessageID.IDS_FeatureExtendedPartialMethods: // semantic check
case MessageID.IDS_TopLevelStatements:
case MessageID.IDS_FeatureInitOnlySetters: // semantic check
case MessageID.IDS_FeatureRecords:
case MessageID.IDS_FeatureTargetTypedConditional: // semantic check
case MessageID.IDS_FeatureCovariantReturnsForOverrides: // semantic check
case MessageID.IDS_FeatureStaticAnonymousFunction: // syntax check
case MessageID.IDS_FeatureModuleInitializers: // semantic check on method attribute
case MessageID.IDS_FeatureDefaultTypeParameterConstraint:
case MessageID.IDS_FeatureVarianceSafetyForStaticInterfaceMembers: // semantic check
return LanguageVersion.CSharp9;
// C# 8.0 features.
case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:
case MessageID.IDS_FeatureCoalesceAssignmentExpression:
case MessageID.IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator:
case MessageID.IDS_FeatureNullableReferenceTypes: // syntax and semantic check
case MessageID.IDS_FeatureIndexOperator: // semantic check
case MessageID.IDS_FeatureRangeOperator: // semantic check
case MessageID.IDS_FeatureAsyncStreams:
case MessageID.IDS_FeatureRecursivePatterns:
case MessageID.IDS_FeatureUsingDeclarations:
case MessageID.IDS_FeatureStaticLocalFunctions:
case MessageID.IDS_FeatureNameShadowingInNestedFunctions:
case MessageID.IDS_FeatureUnmanagedConstructedTypes: // semantic check
case MessageID.IDS_FeatureObsoleteOnPropertyAccessor:
case MessageID.IDS_FeatureReadOnlyMembers:
case MessageID.IDS_DefaultInterfaceImplementation: // semantic check
case MessageID.IDS_OverrideWithConstraints: // semantic check
case MessageID.IDS_FeatureNestedStackalloc: // semantic check
case MessageID.IDS_FeatureNotNullGenericTypeConstraint:// semantic check
case MessageID.IDS_FeatureSwitchExpression:
case MessageID.IDS_FeatureAsyncUsing:
case MessageID.IDS_FeatureNullPointerConstantPattern: //semantic check
return LanguageVersion.CSharp8;
// C# 7.3 features.
case MessageID.IDS_FeatureAttributesOnBackingFields: // semantic check
case MessageID.IDS_FeatureImprovedOverloadCandidates: // semantic check
case MessageID.IDS_FeatureTupleEquality: // semantic check
case MessageID.IDS_FeatureRefReassignment:
case MessageID.IDS_FeatureRefFor:
case MessageID.IDS_FeatureRefForEach:
case MessageID.IDS_FeatureEnumGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureDelegateGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureUnmanagedGenericTypeConstraint: // semantic check
case MessageID.IDS_FeatureStackAllocInitializer:
case MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers: // semantic check
case MessageID.IDS_FeatureExtensibleFixedStatement: // semantic check
case MessageID.IDS_FeatureIndexingMovableFixedBuffers: //semantic check
return LanguageVersion.CSharp7_3;
// C# 7.2 features.
case MessageID.IDS_FeatureNonTrailingNamedArguments: // semantic check
case MessageID.IDS_FeatureLeadingDigitSeparator:
case MessageID.IDS_FeaturePrivateProtected:
case MessageID.IDS_FeatureReadOnlyReferences:
case MessageID.IDS_FeatureRefStructs:
case MessageID.IDS_FeatureReadOnlyStructs:
case MessageID.IDS_FeatureRefExtensionMethods:
case MessageID.IDS_FeatureRefConditional:
return LanguageVersion.CSharp7_2;
// C# 7.1 features.
case MessageID.IDS_FeatureAsyncMain:
case MessageID.IDS_FeatureDefaultLiteral:
case MessageID.IDS_FeatureInferredTupleNames:
case MessageID.IDS_FeatureGenericPatternMatching:
return LanguageVersion.CSharp7_1;
// C# 7 features.
case MessageID.IDS_FeatureBinaryLiteral:
case MessageID.IDS_FeatureDigitSeparator:
case MessageID.IDS_FeatureLocalFunctions:
case MessageID.IDS_FeatureRefLocalsReturns:
case MessageID.IDS_FeaturePatternMatching:
case MessageID.IDS_FeatureThrowExpression:
case MessageID.IDS_FeatureTuples:
case MessageID.IDS_FeatureOutVar:
case MessageID.IDS_FeatureExpressionBodiedAccessor:
case MessageID.IDS_FeatureExpressionBodiedDeOrConstructor:
case MessageID.IDS_FeatureDiscards:
return LanguageVersion.CSharp7;
// C# 6 features.
case MessageID.IDS_FeatureExceptionFilter:
case MessageID.IDS_FeatureAutoPropertyInitializer:
case MessageID.IDS_FeatureNullPropagatingOperator:
case MessageID.IDS_FeatureExpressionBodiedMethod:
case MessageID.IDS_FeatureExpressionBodiedProperty:
case MessageID.IDS_FeatureExpressionBodiedIndexer:
case MessageID.IDS_FeatureNameof:
case MessageID.IDS_FeatureDictionaryInitializer:
case MessageID.IDS_FeatureUsingStatic:
case MessageID.IDS_FeatureInterpolatedStrings:
case MessageID.IDS_AwaitInCatchAndFinally:
case MessageID.IDS_FeatureReadonlyAutoImplementedProperties:
return LanguageVersion.CSharp6;
// C# 5 features.
case MessageID.IDS_FeatureAsync:
return LanguageVersion.CSharp5;
// C# 4 features.
case MessageID.IDS_FeatureDynamic: // Checked in the binder.
case MessageID.IDS_FeatureTypeVariance:
case MessageID.IDS_FeatureNamedArgument:
case MessageID.IDS_FeatureOptionalParameter:
return LanguageVersion.CSharp4;
// C# 3 features.
case MessageID.IDS_FeatureImplicitArray:
case MessageID.IDS_FeatureAnonymousTypes:
case MessageID.IDS_FeatureObjectInitializer:
case MessageID.IDS_FeatureCollectionInitializer:
case MessageID.IDS_FeatureLambda:
case MessageID.IDS_FeatureQueryExpression:
case MessageID.IDS_FeatureExtensionMethod:
case MessageID.IDS_FeaturePartialMethod:
case MessageID.IDS_FeatureImplicitLocal: // Checked in the binder.
case MessageID.IDS_FeatureAutoImplementedProperties:
return LanguageVersion.CSharp3;
// C# 2 features.
case MessageID.IDS_FeatureGenerics: // Also affects crefs.
case MessageID.IDS_FeatureAnonDelegates:
case MessageID.IDS_FeatureGlobalNamespace: // Also affects crefs.
case MessageID.IDS_FeatureFixedBuffer:
case MessageID.IDS_FeatureStaticClasses:
case MessageID.IDS_FeaturePartialTypes:
case MessageID.IDS_FeaturePropertyAccessorMods:
case MessageID.IDS_FeatureExternAlias:
case MessageID.IDS_FeatureIterators:
case MessageID.IDS_FeatureDefault:
case MessageID.IDS_FeatureNullable:
case MessageID.IDS_FeaturePragma: // Checked in the directive parser.
case MessageID.IDS_FeatureSwitchOnBool: // Checked in the binder.
return LanguageVersion.CSharp2;
// Special C# 2 feature: only a warning in C# 1.
case MessageID.IDS_FeatureModuleAttrLoc:
return LanguageVersion.CSharp1;
default:
throw ExceptionUtilities.UnexpectedValue(feature);
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/SolutionCrawler/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.Text;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal static class Extensions
{
public static string ToBase64(this string data)
{
// Write out the message in base64, since it may contain
// user code that can't be represented in xml. (see
// http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=578059)
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
}
public static string DecodeBase64(this string data)
{
var bytes = Convert.FromBase64String(data);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal static class Extensions
{
public static string ToBase64(this string data)
{
// Write out the message in base64, since it may contain
// user code that can't be represented in xml. (see
// http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=578059)
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
}
public static string DecodeBase64(this string data)
{
var bytes = Convert.FromBase64String(data);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/CSharp/Portable/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseLocalFunction), Shared]
internal class CSharpUseLocalFunctionCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
private static readonly TypeSyntax s_objectType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword));
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseLocalFunctionCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseLocalFunctionDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.IsSuppressed;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodesFromDiagnostics = new List<(
LocalDeclarationStatementSyntax declaration,
AnonymousFunctionExpressionSyntax function,
List<ExpressionSyntax> references)>(diagnostics.Length);
var nodesToTrack = new HashSet<SyntaxNode>();
foreach (var diagnostic in diagnostics)
{
var localDeclaration = (LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
var anonymousFunction = (AnonymousFunctionExpressionSyntax)diagnostic.AdditionalLocations[1].FindNode(cancellationToken);
var references = new List<ExpressionSyntax>(diagnostic.AdditionalLocations.Count - 2);
for (var i = 2; i < diagnostic.AdditionalLocations.Count; i++)
{
references.Add((ExpressionSyntax)diagnostic.AdditionalLocations[i].FindNode(getInnermostNodeForTie: true, cancellationToken));
}
nodesFromDiagnostics.Add((localDeclaration, anonymousFunction, references));
nodesToTrack.Add(localDeclaration);
nodesToTrack.Add(anonymousFunction);
nodesToTrack.AddRange(references);
}
var root = editor.OriginalRoot;
var currentRoot = root.TrackNodes(nodesToTrack);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var languageVersion = ((CSharpParseOptions)semanticModel.SyntaxTree.Options).LanguageVersion;
var makeStaticIfPossible = languageVersion >= LanguageVersion.CSharp8 &&
options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value;
// Process declarations in reverse order so that we see the effects of nested
// declarations befor processing the outer decls.
foreach (var (localDeclaration, anonymousFunction, references) in nodesFromDiagnostics.OrderByDescending(nodes => nodes.function.SpanStart))
{
var delegateType = (INamedTypeSymbol)semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType;
var parameterList = GenerateParameterList(anonymousFunction, delegateType.DelegateInvokeMethod);
var makeStatic = MakeStatic(semanticModel, makeStaticIfPossible, localDeclaration, cancellationToken);
var currentLocalDeclaration = currentRoot.GetCurrentNode(localDeclaration);
var currentAnonymousFunction = currentRoot.GetCurrentNode(anonymousFunction);
currentRoot = ReplaceAnonymousWithLocalFunction(
document.Project.Solution.Workspace, currentRoot,
currentLocalDeclaration, currentAnonymousFunction,
delegateType.DelegateInvokeMethod, parameterList, makeStatic);
// these invocations might actually be inside the local function! so we have to do this separately
currentRoot = ReplaceReferences(
document, currentRoot,
delegateType, parameterList,
references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray());
}
editor.ReplaceNode(root, currentRoot);
}
private static bool MakeStatic(
SemanticModel semanticModel,
bool makeStaticIfPossible,
LocalDeclarationStatementSyntax localDeclaration,
CancellationToken cancellationToken)
{
// Determines if we can make the local function 'static'. We can make it static
// if the original lambda did not capture any variables (other than the local
// variable itself). it's ok for the lambda to capture itself as a static-local
// function can reference itself without any problems.
if (makeStaticIfPossible)
{
var localSymbol = semanticModel.GetDeclaredSymbol(
localDeclaration.Declaration.Variables[0], cancellationToken);
var dataFlow = semanticModel.AnalyzeDataFlow(localDeclaration);
if (dataFlow.Succeeded)
{
var capturedVariables = dataFlow.Captured.Remove(localSymbol);
if (capturedVariables.IsEmpty)
{
return true;
}
}
}
return false;
}
private static SyntaxNode ReplaceAnonymousWithLocalFunction(
Workspace workspace, SyntaxNode currentRoot,
LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction,
IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic)
{
var newLocalFunctionStatement = CreateLocalFunctionStatement(localDeclaration, anonymousFunction, delegateMethod, parameterList, makeStatic)
.WithTriviaFrom(localDeclaration)
.WithAdditionalAnnotations(Formatter.Annotation);
var editor = new SyntaxEditor(currentRoot, workspace);
editor.ReplaceNode(localDeclaration, newLocalFunctionStatement);
var anonymousFunctionStatement = anonymousFunction.GetAncestor<StatementSyntax>();
if (anonymousFunctionStatement != localDeclaration)
{
// This is the split decl+init form. Remove the second statement as we're
// merging into the first one.
editor.RemoveNode(anonymousFunctionStatement);
}
return editor.GetChangedRoot();
}
private static SyntaxNode ReplaceReferences(
Document document, SyntaxNode currentRoot,
INamedTypeSymbol delegateType, ParameterListSyntax parameterList,
ImmutableArray<ExpressionSyntax> references)
{
return currentRoot.ReplaceNodes(references, (_ /* nested invocations! */, reference) =>
{
if (reference is InvocationExpressionSyntax invocation)
{
var directInvocation = invocation.Expression is MemberAccessExpressionSyntax memberAccess // it's a .Invoke call
? invocation.WithExpression(memberAccess.Expression).WithTriviaFrom(invocation) // remove it
: invocation;
return WithNewParameterNames(directInvocation, delegateType.DelegateInvokeMethod, parameterList);
}
// It's not an invocation. Wrap the identifier in a cast (which will be remove by the simplifier if unnecessary)
// to ensure we preserve semantics in cases like overload resolution or generic type inference.
return SyntaxGenerator.GetGenerator(document).CastExpression(delegateType, reference);
});
}
private static LocalFunctionStatementSyntax CreateLocalFunctionStatement(
LocalDeclarationStatementSyntax localDeclaration,
AnonymousFunctionExpressionSyntax anonymousFunction,
IMethodSymbol delegateMethod,
ParameterListSyntax parameterList,
bool makeStatic)
{
var modifiers = new SyntaxTokenList();
if (makeStatic)
{
modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword))
{
modifiers = modifiers.Add(anonymousFunction.AsyncKeyword);
}
var returnType = delegateMethod.GenerateReturnTypeSyntax();
var identifier = localDeclaration.Declaration.Variables[0].Identifier;
var typeParameterList = (TypeParameterListSyntax)null;
var constraintClauses = default(SyntaxList<TypeParameterConstraintClauseSyntax>);
var body = anonymousFunction.Body.IsKind(SyntaxKind.Block, out BlockSyntax block)
? block
: null;
var expressionBody = anonymousFunction.Body is ExpressionSyntax expression
? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression)
: null;
var semicolonToken = anonymousFunction.Body is ExpressionSyntax
? localDeclaration.SemicolonToken
: default;
return SyntaxFactory.LocalFunctionStatement(
modifiers, returnType, identifier, typeParameterList, parameterList,
constraintClauses, body, expressionBody, semicolonToken);
}
private static ParameterListSyntax GenerateParameterList(
AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod)
{
var parameterList = TryGetOrCreateParameterList(anonymousFunction);
var i = 0;
return parameterList != null
? parameterList.ReplaceNodes(parameterList.Parameters, (parameterNode, _) => PromoteParameter(parameterNode, delegateMethod.Parameters.ElementAtOrDefault(i++)))
: SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(delegateMethod.Parameters.Select(parameter =>
PromoteParameter(SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()), parameter))));
static ParameterSyntax PromoteParameter(ParameterSyntax parameterNode, IParameterSymbol delegateParameter)
{
// delegateParameter may be null, consider this case: Action x = (a, b) => { };
// we will still fall back to object
if (parameterNode.Type == null)
{
parameterNode = parameterNode.WithType(delegateParameter?.Type.GenerateTypeSyntax() ?? s_objectType);
}
if (delegateParameter?.HasExplicitDefaultValue == true)
{
parameterNode = parameterNode.WithDefault(GetDefaultValue(delegateParameter));
}
return parameterNode;
}
}
private static ParameterListSyntax TryGetOrCreateParameterList(AnonymousFunctionExpressionSyntax anonymousFunction)
{
switch (anonymousFunction)
{
case SimpleLambdaExpressionSyntax simpleLambda:
return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(simpleLambda.Parameter));
case ParenthesizedLambdaExpressionSyntax parenthesizedLambda:
return parenthesizedLambda.ParameterList;
case AnonymousMethodExpressionSyntax anonymousMethod:
return anonymousMethod.ParameterList; // may be null!
default:
throw ExceptionUtilities.UnexpectedValue(anonymousFunction);
}
}
private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpressionSyntax invocation, IMethodSymbol method, ParameterListSyntax newParameterList)
{
return invocation.ReplaceNodes(invocation.ArgumentList.Arguments, (argumentNode, _) =>
{
if (argumentNode.NameColon == null)
{
return argumentNode;
}
var parameterIndex = TryDetermineParameterIndex(argumentNode.NameColon, method);
if (parameterIndex == -1)
{
return argumentNode;
}
var newParameter = newParameterList.Parameters.ElementAtOrDefault(parameterIndex);
if (newParameter == null || newParameter.Identifier.IsMissing)
{
return argumentNode;
}
return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier)));
});
}
private static int TryDetermineParameterIndex(NameColonSyntax argumentNameColon, IMethodSymbol method)
{
var name = argumentNameColon.Name.Identifier.ValueText;
return method.Parameters.IndexOf(p => p.Name == name);
}
private static EqualsValueClauseSyntax GetDefaultValue(IParameterSymbol parameter)
=> SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true));
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_local_function, createChangedDocument, CSharpAnalyzersResources.Use_local_function)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseLocalFunction), Shared]
internal class CSharpUseLocalFunctionCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
private static readonly TypeSyntax s_objectType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword));
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseLocalFunctionCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseLocalFunctionDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.IsSuppressed;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodesFromDiagnostics = new List<(
LocalDeclarationStatementSyntax declaration,
AnonymousFunctionExpressionSyntax function,
List<ExpressionSyntax> references)>(diagnostics.Length);
var nodesToTrack = new HashSet<SyntaxNode>();
foreach (var diagnostic in diagnostics)
{
var localDeclaration = (LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
var anonymousFunction = (AnonymousFunctionExpressionSyntax)diagnostic.AdditionalLocations[1].FindNode(cancellationToken);
var references = new List<ExpressionSyntax>(diagnostic.AdditionalLocations.Count - 2);
for (var i = 2; i < diagnostic.AdditionalLocations.Count; i++)
{
references.Add((ExpressionSyntax)diagnostic.AdditionalLocations[i].FindNode(getInnermostNodeForTie: true, cancellationToken));
}
nodesFromDiagnostics.Add((localDeclaration, anonymousFunction, references));
nodesToTrack.Add(localDeclaration);
nodesToTrack.Add(anonymousFunction);
nodesToTrack.AddRange(references);
}
var root = editor.OriginalRoot;
var currentRoot = root.TrackNodes(nodesToTrack);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var languageVersion = ((CSharpParseOptions)semanticModel.SyntaxTree.Options).LanguageVersion;
var makeStaticIfPossible = languageVersion >= LanguageVersion.CSharp8 &&
options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value;
// Process declarations in reverse order so that we see the effects of nested
// declarations befor processing the outer decls.
foreach (var (localDeclaration, anonymousFunction, references) in nodesFromDiagnostics.OrderByDescending(nodes => nodes.function.SpanStart))
{
var delegateType = (INamedTypeSymbol)semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType;
var parameterList = GenerateParameterList(anonymousFunction, delegateType.DelegateInvokeMethod);
var makeStatic = MakeStatic(semanticModel, makeStaticIfPossible, localDeclaration, cancellationToken);
var currentLocalDeclaration = currentRoot.GetCurrentNode(localDeclaration);
var currentAnonymousFunction = currentRoot.GetCurrentNode(anonymousFunction);
currentRoot = ReplaceAnonymousWithLocalFunction(
document.Project.Solution.Workspace, currentRoot,
currentLocalDeclaration, currentAnonymousFunction,
delegateType.DelegateInvokeMethod, parameterList, makeStatic);
// these invocations might actually be inside the local function! so we have to do this separately
currentRoot = ReplaceReferences(
document, currentRoot,
delegateType, parameterList,
references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray());
}
editor.ReplaceNode(root, currentRoot);
}
private static bool MakeStatic(
SemanticModel semanticModel,
bool makeStaticIfPossible,
LocalDeclarationStatementSyntax localDeclaration,
CancellationToken cancellationToken)
{
// Determines if we can make the local function 'static'. We can make it static
// if the original lambda did not capture any variables (other than the local
// variable itself). it's ok for the lambda to capture itself as a static-local
// function can reference itself without any problems.
if (makeStaticIfPossible)
{
var localSymbol = semanticModel.GetDeclaredSymbol(
localDeclaration.Declaration.Variables[0], cancellationToken);
var dataFlow = semanticModel.AnalyzeDataFlow(localDeclaration);
if (dataFlow.Succeeded)
{
var capturedVariables = dataFlow.Captured.Remove(localSymbol);
if (capturedVariables.IsEmpty)
{
return true;
}
}
}
return false;
}
private static SyntaxNode ReplaceAnonymousWithLocalFunction(
Workspace workspace, SyntaxNode currentRoot,
LocalDeclarationStatementSyntax localDeclaration, AnonymousFunctionExpressionSyntax anonymousFunction,
IMethodSymbol delegateMethod, ParameterListSyntax parameterList, bool makeStatic)
{
var newLocalFunctionStatement = CreateLocalFunctionStatement(localDeclaration, anonymousFunction, delegateMethod, parameterList, makeStatic)
.WithTriviaFrom(localDeclaration)
.WithAdditionalAnnotations(Formatter.Annotation);
var editor = new SyntaxEditor(currentRoot, workspace);
editor.ReplaceNode(localDeclaration, newLocalFunctionStatement);
var anonymousFunctionStatement = anonymousFunction.GetAncestor<StatementSyntax>();
if (anonymousFunctionStatement != localDeclaration)
{
// This is the split decl+init form. Remove the second statement as we're
// merging into the first one.
editor.RemoveNode(anonymousFunctionStatement);
}
return editor.GetChangedRoot();
}
private static SyntaxNode ReplaceReferences(
Document document, SyntaxNode currentRoot,
INamedTypeSymbol delegateType, ParameterListSyntax parameterList,
ImmutableArray<ExpressionSyntax> references)
{
return currentRoot.ReplaceNodes(references, (_ /* nested invocations! */, reference) =>
{
if (reference is InvocationExpressionSyntax invocation)
{
var directInvocation = invocation.Expression is MemberAccessExpressionSyntax memberAccess // it's a .Invoke call
? invocation.WithExpression(memberAccess.Expression).WithTriviaFrom(invocation) // remove it
: invocation;
return WithNewParameterNames(directInvocation, delegateType.DelegateInvokeMethod, parameterList);
}
// It's not an invocation. Wrap the identifier in a cast (which will be remove by the simplifier if unnecessary)
// to ensure we preserve semantics in cases like overload resolution or generic type inference.
return SyntaxGenerator.GetGenerator(document).CastExpression(delegateType, reference);
});
}
private static LocalFunctionStatementSyntax CreateLocalFunctionStatement(
LocalDeclarationStatementSyntax localDeclaration,
AnonymousFunctionExpressionSyntax anonymousFunction,
IMethodSymbol delegateMethod,
ParameterListSyntax parameterList,
bool makeStatic)
{
var modifiers = new SyntaxTokenList();
if (makeStatic)
{
modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword))
{
modifiers = modifiers.Add(anonymousFunction.AsyncKeyword);
}
var returnType = delegateMethod.GenerateReturnTypeSyntax();
var identifier = localDeclaration.Declaration.Variables[0].Identifier;
var typeParameterList = (TypeParameterListSyntax)null;
var constraintClauses = default(SyntaxList<TypeParameterConstraintClauseSyntax>);
var body = anonymousFunction.Body.IsKind(SyntaxKind.Block, out BlockSyntax block)
? block
: null;
var expressionBody = anonymousFunction.Body is ExpressionSyntax expression
? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression)
: null;
var semicolonToken = anonymousFunction.Body is ExpressionSyntax
? localDeclaration.SemicolonToken
: default;
return SyntaxFactory.LocalFunctionStatement(
modifiers, returnType, identifier, typeParameterList, parameterList,
constraintClauses, body, expressionBody, semicolonToken);
}
private static ParameterListSyntax GenerateParameterList(
AnonymousFunctionExpressionSyntax anonymousFunction, IMethodSymbol delegateMethod)
{
var parameterList = TryGetOrCreateParameterList(anonymousFunction);
var i = 0;
return parameterList != null
? parameterList.ReplaceNodes(parameterList.Parameters, (parameterNode, _) => PromoteParameter(parameterNode, delegateMethod.Parameters.ElementAtOrDefault(i++)))
: SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(delegateMethod.Parameters.Select(parameter =>
PromoteParameter(SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()), parameter))));
static ParameterSyntax PromoteParameter(ParameterSyntax parameterNode, IParameterSymbol delegateParameter)
{
// delegateParameter may be null, consider this case: Action x = (a, b) => { };
// we will still fall back to object
if (parameterNode.Type == null)
{
parameterNode = parameterNode.WithType(delegateParameter?.Type.GenerateTypeSyntax() ?? s_objectType);
}
if (delegateParameter?.HasExplicitDefaultValue == true)
{
parameterNode = parameterNode.WithDefault(GetDefaultValue(delegateParameter));
}
return parameterNode;
}
}
private static ParameterListSyntax TryGetOrCreateParameterList(AnonymousFunctionExpressionSyntax anonymousFunction)
{
switch (anonymousFunction)
{
case SimpleLambdaExpressionSyntax simpleLambda:
return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(simpleLambda.Parameter));
case ParenthesizedLambdaExpressionSyntax parenthesizedLambda:
return parenthesizedLambda.ParameterList;
case AnonymousMethodExpressionSyntax anonymousMethod:
return anonymousMethod.ParameterList; // may be null!
default:
throw ExceptionUtilities.UnexpectedValue(anonymousFunction);
}
}
private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpressionSyntax invocation, IMethodSymbol method, ParameterListSyntax newParameterList)
{
return invocation.ReplaceNodes(invocation.ArgumentList.Arguments, (argumentNode, _) =>
{
if (argumentNode.NameColon == null)
{
return argumentNode;
}
var parameterIndex = TryDetermineParameterIndex(argumentNode.NameColon, method);
if (parameterIndex == -1)
{
return argumentNode;
}
var newParameter = newParameterList.Parameters.ElementAtOrDefault(parameterIndex);
if (newParameter == null || newParameter.Identifier.IsMissing)
{
return argumentNode;
}
return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier)));
});
}
private static int TryDetermineParameterIndex(NameColonSyntax argumentNameColon, IMethodSymbol method)
{
var name = argumentNameColon.Name.Identifier.ValueText;
return method.Parameters.IndexOf(p => p.Name == name);
}
private static EqualsValueClauseSyntax GetDefaultValue(IParameterSymbol parameter)
=> SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true));
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_local_function, createChangedDocument, CSharpAnalyzersResources.Use_local_function)
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Test/Extensions/ITextExtensionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
{
public class ITextExtensionsTests
{
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_EmptyLineReturnsEmptyString()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(string.Empty, 0);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" ", 0);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\t", 0);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t ", 0);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLine()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo", 0);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" Goo", 0);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\tGoo", 0);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t Goo", 0);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_EmptySecondLineReturnsEmptyString()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n", 5);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n ", 5);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\t", 5);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t ", 5);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLine()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\nGoo", 5);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n Goo", 5);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\tGoo", 5);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t Goo", 5);
Assert.Equal(" \t ", leadingWhitespace);
}
private static string GetLeadingWhitespaceOfLineAtPosition(string code, int position)
{
var text = SourceText.From(code);
return text.GetLeadingWhitespaceOfLineAtPosition(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.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
{
public class ITextExtensionsTests
{
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_EmptyLineReturnsEmptyString()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(string.Empty, 0);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" ", 0);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\t", 0);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t ", 0);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLine()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo", 0);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" Goo", 0);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\tGoo", 0);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t Goo", 0);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_EmptySecondLineReturnsEmptyString()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n", 5);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n ", 5);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\t", 5);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t ", 5);
Assert.Equal(" \t ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLine()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\nGoo", 5);
Assert.Equal(string.Empty, leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace1()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n Goo", 5);
Assert.Equal(" ", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace2()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n\t\tGoo", 5);
Assert.Equal("\t\t", leadingWhitespace);
}
[Fact]
public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace3()
{
var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Goo\r\n \t Goo", 5);
Assert.Equal(" \t ", leadingWhitespace);
}
private static string GetLeadingWhitespaceOfLineAtPosition(string code, int position)
{
var text = SourceText.From(code);
return text.GetLeadingWhitespaceOfLineAtPosition(position);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Core/Shared/Utilities/VirtualTreePoint.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal struct VirtualTreePoint : IComparable<VirtualTreePoint>, IEquatable<VirtualTreePoint>
{
private readonly SyntaxTree _tree;
private readonly SourceText _text;
private readonly int _position;
private readonly int _virtualSpaces;
public VirtualTreePoint(SyntaxTree tree, SourceText text, int position, int virtualSpaces = 0)
{
Contract.ThrowIfNull(tree);
Contract.ThrowIfFalse(position >= 0 && position <= tree.Length);
Contract.ThrowIfFalse(virtualSpaces >= 0);
_tree = tree;
_text = text;
_position = position;
_virtualSpaces = virtualSpaces;
}
public static bool operator !=(VirtualTreePoint left, VirtualTreePoint right)
=> !(left == right);
public static bool operator <(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) < 0;
public static bool operator <=(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) <= 0;
public static bool operator ==(VirtualTreePoint left, VirtualTreePoint right)
=> object.Equals(left, right);
public static bool operator >(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) > 0;
public static bool operator >=(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) >= 0;
public bool IsInVirtualSpace
{
get { return _virtualSpaces != 0; }
}
public int Position => _position;
public int VirtualSpaces => _virtualSpaces;
public SourceText Text => _text;
public SyntaxTree Tree => _tree;
public int CompareTo(VirtualTreePoint other)
{
if (Text != other.Text)
{
throw new InvalidOperationException(EditorFeaturesResources.Can_t_compare_positions_from_different_text_snapshots);
}
return ComparerWithState.CompareTo(this, other, s_comparers);
}
private static readonly ImmutableArray<Func<VirtualTreePoint, IComparable>> s_comparers =
ImmutableArray.Create<Func<VirtualTreePoint, IComparable>>(p => p.Position, prop => prop.VirtualSpaces);
public bool Equals(VirtualTreePoint other)
=> CompareTo(other) == 0;
public override bool Equals(object? obj)
=> (obj is VirtualTreePoint) && Equals((VirtualTreePoint)obj);
public override int GetHashCode()
=> Text.GetHashCode() ^ Position.GetHashCode() ^ VirtualSpaces.GetHashCode();
public override string ToString()
=> $"VirtualTreePoint {{ Tree: '{Tree}', Text: '{Text}', Position: '{Position}', VirtualSpaces '{VirtualSpaces}' }}";
public TextLine GetContainingLine()
=> Text.Lines.GetLineFromPosition(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.Immutable;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal struct VirtualTreePoint : IComparable<VirtualTreePoint>, IEquatable<VirtualTreePoint>
{
private readonly SyntaxTree _tree;
private readonly SourceText _text;
private readonly int _position;
private readonly int _virtualSpaces;
public VirtualTreePoint(SyntaxTree tree, SourceText text, int position, int virtualSpaces = 0)
{
Contract.ThrowIfNull(tree);
Contract.ThrowIfFalse(position >= 0 && position <= tree.Length);
Contract.ThrowIfFalse(virtualSpaces >= 0);
_tree = tree;
_text = text;
_position = position;
_virtualSpaces = virtualSpaces;
}
public static bool operator !=(VirtualTreePoint left, VirtualTreePoint right)
=> !(left == right);
public static bool operator <(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) < 0;
public static bool operator <=(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) <= 0;
public static bool operator ==(VirtualTreePoint left, VirtualTreePoint right)
=> object.Equals(left, right);
public static bool operator >(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) > 0;
public static bool operator >=(VirtualTreePoint left, VirtualTreePoint right)
=> left.CompareTo(right) >= 0;
public bool IsInVirtualSpace
{
get { return _virtualSpaces != 0; }
}
public int Position => _position;
public int VirtualSpaces => _virtualSpaces;
public SourceText Text => _text;
public SyntaxTree Tree => _tree;
public int CompareTo(VirtualTreePoint other)
{
if (Text != other.Text)
{
throw new InvalidOperationException(EditorFeaturesResources.Can_t_compare_positions_from_different_text_snapshots);
}
return ComparerWithState.CompareTo(this, other, s_comparers);
}
private static readonly ImmutableArray<Func<VirtualTreePoint, IComparable>> s_comparers =
ImmutableArray.Create<Func<VirtualTreePoint, IComparable>>(p => p.Position, prop => prop.VirtualSpaces);
public bool Equals(VirtualTreePoint other)
=> CompareTo(other) == 0;
public override bool Equals(object? obj)
=> (obj is VirtualTreePoint) && Equals((VirtualTreePoint)obj);
public override int GetHashCode()
=> Text.GetHashCode() ^ Position.GetHashCode() ^ VirtualSpaces.GetHashCode();
public override string ToString()
=> $"VirtualTreePoint {{ Tree: '{Tree}', Text: '{Text}', Position: '{Position}', VirtualSpaces '{VirtualSpaces}' }}";
public TextLine GetContainingLine()
=> Text.Lines.GetLineFromPosition(Position);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceMarginViewMarginProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin
{
[Export(typeof(IWpfTextViewMarginProvider))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[Name(nameof(InheritanceMarginViewMarginProvider))]
[MarginContainer(PredefinedMarginNames.Left)]
[Order(After = PredefinedMarginNames.Glyph)]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal class InheritanceMarginViewMarginProvider : IWpfTextViewMarginProvider
{
private readonly IViewTagAggregatorFactoryService _tagAggregatorFactoryService;
private readonly IThreadingContext _threadingContext;
private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter;
private readonly IClassificationFormatMapService _classificationFormatMapService;
private readonly ClassificationTypeMap _classificationTypeMap;
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IEditorFormatMapService _editorFormatMapService;
private readonly IAsynchronousOperationListenerProvider _listenerProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InheritanceMarginViewMarginProvider(
IThreadingContext threadingContext,
IStreamingFindUsagesPresenter streamingFindUsagesPresenter,
ClassificationTypeMap classificationTypeMap,
IClassificationFormatMapService classificationFormatMapService,
IUIThreadOperationExecutor operationExecutor,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IEditorFormatMapService editorFormatMapService,
IAsynchronousOperationListenerProvider listenerProvider)
{
_threadingContext = threadingContext;
_streamingFindUsagesPresenter = streamingFindUsagesPresenter;
_classificationTypeMap = classificationTypeMap;
_classificationFormatMapService = classificationFormatMapService;
_operationExecutor = operationExecutor;
_tagAggregatorFactoryService = tagAggregatorFactoryService;
_editorFormatMapService = editorFormatMapService;
_listenerProvider = listenerProvider;
}
public IWpfTextViewMargin? CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer)
{
var textView = wpfTextViewHost.TextView;
var tagAggregator = _tagAggregatorFactoryService.CreateTagAggregator<InheritanceMarginTag>(textView);
var editorFormatMap = _editorFormatMapService.GetEditorFormatMap(textView);
var document = wpfTextViewHost.TextView.TextBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
var optionService = document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
var listener = _listenerProvider.GetListener(FeatureAttribute.InheritanceMargin);
return new InheritanceMarginViewMargin(
textView,
_threadingContext,
_streamingFindUsagesPresenter,
_operationExecutor,
_classificationFormatMapService.GetClassificationFormatMap("tooltip"),
_classificationTypeMap,
tagAggregator,
editorFormatMap,
optionService,
listener,
document.Project.Language);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin
{
[Export(typeof(IWpfTextViewMarginProvider))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[Name(nameof(InheritanceMarginViewMarginProvider))]
[MarginContainer(PredefinedMarginNames.Left)]
[Order(After = PredefinedMarginNames.Glyph)]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal class InheritanceMarginViewMarginProvider : IWpfTextViewMarginProvider
{
private readonly IViewTagAggregatorFactoryService _tagAggregatorFactoryService;
private readonly IThreadingContext _threadingContext;
private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter;
private readonly IClassificationFormatMapService _classificationFormatMapService;
private readonly ClassificationTypeMap _classificationTypeMap;
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly IEditorFormatMapService _editorFormatMapService;
private readonly IAsynchronousOperationListenerProvider _listenerProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InheritanceMarginViewMarginProvider(
IThreadingContext threadingContext,
IStreamingFindUsagesPresenter streamingFindUsagesPresenter,
ClassificationTypeMap classificationTypeMap,
IClassificationFormatMapService classificationFormatMapService,
IUIThreadOperationExecutor operationExecutor,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IEditorFormatMapService editorFormatMapService,
IAsynchronousOperationListenerProvider listenerProvider)
{
_threadingContext = threadingContext;
_streamingFindUsagesPresenter = streamingFindUsagesPresenter;
_classificationTypeMap = classificationTypeMap;
_classificationFormatMapService = classificationFormatMapService;
_operationExecutor = operationExecutor;
_tagAggregatorFactoryService = tagAggregatorFactoryService;
_editorFormatMapService = editorFormatMapService;
_listenerProvider = listenerProvider;
}
public IWpfTextViewMargin? CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer)
{
var textView = wpfTextViewHost.TextView;
var tagAggregator = _tagAggregatorFactoryService.CreateTagAggregator<InheritanceMarginTag>(textView);
var editorFormatMap = _editorFormatMapService.GetEditorFormatMap(textView);
var document = wpfTextViewHost.TextView.TextBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
var optionService = document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
var listener = _listenerProvider.GetListener(FeatureAttribute.InheritanceMargin);
return new InheritanceMarginViewMargin(
textView,
_threadingContext,
_streamingFindUsagesPresenter,
_operationExecutor,
_classificationFormatMapService.GetClassificationFormatMap("tooltip"),
_classificationTypeMap,
tagAggregator,
editorFormatMap,
optionService,
listener,
document.Project.Language);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/SolutionExplorer_OutOfProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
using Roslyn.Utilities;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public partial class SolutionExplorer_OutOfProc : OutOfProcComponent
{
public Verifier Verify { get; }
private readonly SolutionExplorer_InProc _inProc;
private readonly VisualStudioInstance _instance;
public SolutionExplorer_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_instance = visualStudioInstance;
_inProc = CreateInProcComponent<SolutionExplorer_InProc>(visualStudioInstance);
Verify = new Verifier(this);
}
public void CloseSolution(bool saveFirst = false)
=> _inProc.CloseSolution(saveFirst);
/// <summary>
/// The full file path to the solution file.
/// </summary>
public string SolutionFileFullPath => _inProc.SolutionFileFullPath;
/// <summary>
/// Creates and loads a new solution in the host process, optionally saving the existing solution if one exists.
/// </summary>
public void CreateSolution(string solutionName, bool saveExistingSolutionIfExists = false)
=> _inProc.CreateSolution(solutionName, saveExistingSolutionIfExists);
public void CreateSolution(string solutionName, XElement solutionElement)
=> _inProc.CreateSolution(solutionName, solutionElement.ToString());
public void OpenSolution(string path, bool saveExistingSolutionIfExists = false)
=> _inProc.OpenSolution(path, saveExistingSolutionIfExists);
public void AddProject(ProjectUtils.Project projectName, string projectTemplate, string languageName)
{
_inProc.AddProject(projectName.Name, projectTemplate, languageName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddCustomProject(ProjectUtils.Project projectName, string projectFileExtension, string projectFileContent)
{
_inProc.AddCustomProject(projectName.Name, projectFileExtension, projectFileContent);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddProjectReference(ProjectUtils.Project fromProjectName, ProjectUtils.ProjectReference toProjectName)
{
_inProc.AddProjectReference(fromProjectName.Name, toProjectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveProjectReference(ProjectUtils.Project projectName, ProjectUtils.ProjectReference projectReferenceName)
{
_inProc.RemoveProjectReference(projectName.Name, projectReferenceName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddMetadataReference(ProjectUtils.AssemblyReference fullyQualifiedAssemblyName, ProjectUtils.Project projectName)
{
_inProc.AddMetadataReference(fullyQualifiedAssemblyName.Name, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveMetadataReference(ProjectUtils.AssemblyReference assemblyName, ProjectUtils.Project projectName)
{
_inProc.RemoveMetadataReference(assemblyName.Name, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddAnalyzerReference(string filePath, ProjectUtils.Project projectName)
{
_inProc.AddAnalyzerReference(filePath, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveAnalyzerReference(string filePath, ProjectUtils.Project projectName)
{
_inProc.RemoveAnalyzerReference(filePath, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void SetLanguageVersion(ProjectUtils.Project projectName, string languageVersion)
{
_inProc.SetLanguageVersion(projectName.Name, languageVersion);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
/// <summary>
/// Add a PackageReference to the specified project. Generally this should be followed up by
/// a call to <see cref="RestoreNuGetPackages"/>.
/// </summary>
public void AddPackageReference(ProjectUtils.Project project, ProjectUtils.PackageReference package)
=> _inProc.AddPackageReference(project.Name, package.Name, package.Version);
/// <summary>
/// Remove a PackageReference from the specified project. Generally this should be followed up by
/// a call to <see cref="RestoreNuGetPackages"/>.
/// </summary>
public void RemovePackageReference(ProjectUtils.Project project, ProjectUtils.PackageReference package)
=> _inProc.RemovePackageReference(project.Name, package.Name);
public void CleanUpOpenSolution()
=> _inProc.CleanUpOpenSolution();
public void AddFile(ProjectUtils.Project project, string fileName, string? contents = null, bool open = false)
=> _inProc.AddFile(project.Name, fileName, contents, open);
public void SetFileContents(ProjectUtils.Project project, string fileName, string contents)
=> _inProc.SetFileContents(project.Name, fileName, contents);
public string GetFileContents(ProjectUtils.Project project, string fileName)
=> _inProc.GetFileContents(project.Name, fileName);
public void BuildSolution()
=> _inProc.BuildSolution();
public void OpenFileWithDesigner(ProjectUtils.Project project, string fileName)
=> _inProc.OpenFileWithDesigner(project.Name, fileName);
public void OpenFile(ProjectUtils.Project project, string fileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.OpenFile(project.Name, fileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void UpdateFile(string projectName, string fileName, string contents, bool open = false)
=> _inProc.UpdateFile(projectName, fileName, contents, open);
public void RenameFile(ProjectUtils.Project project, string oldFileName, string newFileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.RenameFile(project.Name, oldFileName, newFileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RenameFileViaDTE(ProjectUtils.Project project, string oldFileName, string newFileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.RenameFileViaDTE(project.Name, oldFileName, newFileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void CloseDesignerFile(ProjectUtils.Project project, string fileName, bool saveFile)
=> _inProc.CloseDesignerFile(project.Name, fileName, saveFile);
public void CloseCodeFile(ProjectUtils.Project project, string fileName, bool saveFile)
=> _inProc.CloseCodeFile(project.Name, fileName, saveFile);
public void SaveFile(ProjectUtils.Project project, string fileName)
=> _inProc.SaveFile(project.Name, fileName);
public void ReloadProject(ProjectUtils.Project project)
{
Contract.ThrowIfNull(project.RelativePath);
_inProc.ReloadProject(project.RelativePath);
}
public void RestoreNuGetPackages(ProjectUtils.Project project)
=> _inProc.RestoreNuGetPackages(project.Name);
public void SaveAll()
=> _inProc.SaveAll();
public void ShowOutputWindow()
=> _inProc.ShowOutputWindow();
public void UnloadProject(ProjectUtils.Project project)
=> _inProc.UnloadProject(project.Name);
public string[] GetProjectReferences(ProjectUtils.Project project)
=> _inProc.GetProjectReferences(project.Name);
public string[] GetAssemblyReferences(ProjectUtils.Project project)
=> _inProc.GetAssemblyReferences(project.Name);
/// <summary>
/// Selects an item named by the <paramref name="itemName"/> parameter.
/// Note that this selects the first item of the given name found. In situations where
/// there may be more than one item of a given name, use <see cref="SelectItemAtPath(string[])"/>
/// instead.
/// </summary>
public void SelectItem(string itemName)
=> _inProc.SelectItem(itemName);
/// <summary>
/// Selects the specific item at the given "path".
/// </summary>
public void SelectItemAtPath(params string[] path)
=> _inProc.SelectItemAtPath(path);
/// <summary>
/// Returns the names of the immediate children of the given item.
/// Note that this uses the first item of the given name found. In situations where there
/// may be more than one item of a given name, use <see cref="GetChildrenOfItemAtPath(string[])"/>
/// instead.
/// </summary>
public string[] GetChildrenOfItem(string itemName)
=> _inProc.GetChildrenOfItem(itemName);
/// <summary>
/// Returns the names of the immediate children of the item at the given "path".
/// </summary>
public string[] GetChildrenOfItemAtPath(params string[] path)
=> _inProc.GetChildrenOfItemAtPath(path);
public void ClearBuildOutputWindowPane()
=> _inProc.ClearBuildOutputWindowPane();
public void WaitForBuildToFinish()
=> _inProc.WaitForBuildToFinish();
public void EditProjectFile(ProjectUtils.Project project)
=> _inProc.EditProjectFile(project.Name);
public void AddStandaloneFile(string fileName)
=> _inProc.AddStandaloneFile(fileName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Xml.Linq;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
using Roslyn.Utilities;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public partial class SolutionExplorer_OutOfProc : OutOfProcComponent
{
public Verifier Verify { get; }
private readonly SolutionExplorer_InProc _inProc;
private readonly VisualStudioInstance _instance;
public SolutionExplorer_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_instance = visualStudioInstance;
_inProc = CreateInProcComponent<SolutionExplorer_InProc>(visualStudioInstance);
Verify = new Verifier(this);
}
public void CloseSolution(bool saveFirst = false)
=> _inProc.CloseSolution(saveFirst);
/// <summary>
/// The full file path to the solution file.
/// </summary>
public string SolutionFileFullPath => _inProc.SolutionFileFullPath;
/// <summary>
/// Creates and loads a new solution in the host process, optionally saving the existing solution if one exists.
/// </summary>
public void CreateSolution(string solutionName, bool saveExistingSolutionIfExists = false)
=> _inProc.CreateSolution(solutionName, saveExistingSolutionIfExists);
public void CreateSolution(string solutionName, XElement solutionElement)
=> _inProc.CreateSolution(solutionName, solutionElement.ToString());
public void OpenSolution(string path, bool saveExistingSolutionIfExists = false)
=> _inProc.OpenSolution(path, saveExistingSolutionIfExists);
public void AddProject(ProjectUtils.Project projectName, string projectTemplate, string languageName)
{
_inProc.AddProject(projectName.Name, projectTemplate, languageName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddCustomProject(ProjectUtils.Project projectName, string projectFileExtension, string projectFileContent)
{
_inProc.AddCustomProject(projectName.Name, projectFileExtension, projectFileContent);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddProjectReference(ProjectUtils.Project fromProjectName, ProjectUtils.ProjectReference toProjectName)
{
_inProc.AddProjectReference(fromProjectName.Name, toProjectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveProjectReference(ProjectUtils.Project projectName, ProjectUtils.ProjectReference projectReferenceName)
{
_inProc.RemoveProjectReference(projectName.Name, projectReferenceName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddMetadataReference(ProjectUtils.AssemblyReference fullyQualifiedAssemblyName, ProjectUtils.Project projectName)
{
_inProc.AddMetadataReference(fullyQualifiedAssemblyName.Name, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveMetadataReference(ProjectUtils.AssemblyReference assemblyName, ProjectUtils.Project projectName)
{
_inProc.RemoveMetadataReference(assemblyName.Name, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void AddAnalyzerReference(string filePath, ProjectUtils.Project projectName)
{
_inProc.AddAnalyzerReference(filePath, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RemoveAnalyzerReference(string filePath, ProjectUtils.Project projectName)
{
_inProc.RemoveAnalyzerReference(filePath, projectName.Name);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void SetLanguageVersion(ProjectUtils.Project projectName, string languageVersion)
{
_inProc.SetLanguageVersion(projectName.Name, languageVersion);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
/// <summary>
/// Add a PackageReference to the specified project. Generally this should be followed up by
/// a call to <see cref="RestoreNuGetPackages"/>.
/// </summary>
public void AddPackageReference(ProjectUtils.Project project, ProjectUtils.PackageReference package)
=> _inProc.AddPackageReference(project.Name, package.Name, package.Version);
/// <summary>
/// Remove a PackageReference from the specified project. Generally this should be followed up by
/// a call to <see cref="RestoreNuGetPackages"/>.
/// </summary>
public void RemovePackageReference(ProjectUtils.Project project, ProjectUtils.PackageReference package)
=> _inProc.RemovePackageReference(project.Name, package.Name);
public void CleanUpOpenSolution()
=> _inProc.CleanUpOpenSolution();
public void AddFile(ProjectUtils.Project project, string fileName, string? contents = null, bool open = false)
=> _inProc.AddFile(project.Name, fileName, contents, open);
public void SetFileContents(ProjectUtils.Project project, string fileName, string contents)
=> _inProc.SetFileContents(project.Name, fileName, contents);
public string GetFileContents(ProjectUtils.Project project, string fileName)
=> _inProc.GetFileContents(project.Name, fileName);
public void BuildSolution()
=> _inProc.BuildSolution();
public void OpenFileWithDesigner(ProjectUtils.Project project, string fileName)
=> _inProc.OpenFileWithDesigner(project.Name, fileName);
public void OpenFile(ProjectUtils.Project project, string fileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.OpenFile(project.Name, fileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void UpdateFile(string projectName, string fileName, string contents, bool open = false)
=> _inProc.UpdateFile(projectName, fileName, contents, open);
public void RenameFile(ProjectUtils.Project project, string oldFileName, string newFileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.RenameFile(project.Name, oldFileName, newFileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void RenameFileViaDTE(ProjectUtils.Project project, string oldFileName, string newFileName)
{
// Wireup to open files can happen asynchronously in the case we're being notified of changes on background threads.
_inProc.RenameFileViaDTE(project.Name, oldFileName, newFileName);
_instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
}
public void CloseDesignerFile(ProjectUtils.Project project, string fileName, bool saveFile)
=> _inProc.CloseDesignerFile(project.Name, fileName, saveFile);
public void CloseCodeFile(ProjectUtils.Project project, string fileName, bool saveFile)
=> _inProc.CloseCodeFile(project.Name, fileName, saveFile);
public void SaveFile(ProjectUtils.Project project, string fileName)
=> _inProc.SaveFile(project.Name, fileName);
public void ReloadProject(ProjectUtils.Project project)
{
Contract.ThrowIfNull(project.RelativePath);
_inProc.ReloadProject(project.RelativePath);
}
public void RestoreNuGetPackages(ProjectUtils.Project project)
=> _inProc.RestoreNuGetPackages(project.Name);
public void SaveAll()
=> _inProc.SaveAll();
public void ShowOutputWindow()
=> _inProc.ShowOutputWindow();
public void UnloadProject(ProjectUtils.Project project)
=> _inProc.UnloadProject(project.Name);
public string[] GetProjectReferences(ProjectUtils.Project project)
=> _inProc.GetProjectReferences(project.Name);
public string[] GetAssemblyReferences(ProjectUtils.Project project)
=> _inProc.GetAssemblyReferences(project.Name);
/// <summary>
/// Selects an item named by the <paramref name="itemName"/> parameter.
/// Note that this selects the first item of the given name found. In situations where
/// there may be more than one item of a given name, use <see cref="SelectItemAtPath(string[])"/>
/// instead.
/// </summary>
public void SelectItem(string itemName)
=> _inProc.SelectItem(itemName);
/// <summary>
/// Selects the specific item at the given "path".
/// </summary>
public void SelectItemAtPath(params string[] path)
=> _inProc.SelectItemAtPath(path);
/// <summary>
/// Returns the names of the immediate children of the given item.
/// Note that this uses the first item of the given name found. In situations where there
/// may be more than one item of a given name, use <see cref="GetChildrenOfItemAtPath(string[])"/>
/// instead.
/// </summary>
public string[] GetChildrenOfItem(string itemName)
=> _inProc.GetChildrenOfItem(itemName);
/// <summary>
/// Returns the names of the immediate children of the item at the given "path".
/// </summary>
public string[] GetChildrenOfItemAtPath(params string[] path)
=> _inProc.GetChildrenOfItemAtPath(path);
public void ClearBuildOutputWindowPane()
=> _inProc.ClearBuildOutputWindowPane();
public void WaitForBuildToFinish()
=> _inProc.WaitForBuildToFinish();
public void EditProjectFile(ProjectUtils.Project project)
=> _inProc.EditProjectFile(project.Name);
public void AddStandaloneFile(string fileName)
=> _inProc.AddStandaloneFile(fileName);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingSolutionExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingSolutionExtensions
{
public static int GetWorkspaceVersion(this Solution solution)
=> solution.WorkspaceVersion;
public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken)
=> new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(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.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingSolutionExtensions
{
public static int GetWorkspaceVersion(this Solution solution)
=> solution.WorkspaceVersion;
public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken)
=> new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false));
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/CommandLine/CommandLineDiagnosticFormatterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class CommandLineDiagnosticFormatterTests
{
[ConditionalFact(typeof(WindowsOnly))]
public void GetPathNameRelativeToBaseDirectory()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\..\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleRootPaths_1()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"temp.cs", formatter.RelativizeNormalizedPath(@"c:\temp.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleRootPaths_2()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\A\B",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"C\D\temp.cs", formatter.RelativizeNormalizedPath(@"c:\A\B\C\D\temp.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleDirectoriesWithSamePrefix_1()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\AB",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"c:\ABCD\file.cs", formatter.RelativizeNormalizedPath(@"c:\ABCD\file.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleDirectoriesWithSamePrefix_2()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\ABCD",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"c:\AB\file.cs", formatter.RelativizeNormalizedPath(@"c:\AB\file.cs"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class CommandLineDiagnosticFormatterTests
{
[ConditionalFact(typeof(WindowsOnly))]
public void GetPathNameRelativeToBaseDirectory()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\..\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleRootPaths_1()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"temp.cs", formatter.RelativizeNormalizedPath(@"c:\temp.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleRootPaths_2()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\A\B",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"C\D\temp.cs", formatter.RelativizeNormalizedPath(@"c:\A\B\C\D\temp.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleDirectoriesWithSamePrefix_1()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\AB",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"c:\ABCD\file.cs", formatter.RelativizeNormalizedPath(@"c:\ABCD\file.cs"));
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(14725, "https://github.com/dotnet/roslyn/issues/14725")]
public void RelativizeNormalizedPathShouldHandleDirectoriesWithSamePrefix_2()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"C:\ABCD",
displayFullPaths: false,
displayEndLocations: false);
Assert.Equal(@"c:\AB\file.cs", formatter.RelativizeNormalizedPath(@"c:\AB\file.cs"));
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Core/Shared/Tagging/Utilities/TagSpanIntervalTree.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
/// <summary>
/// A tag span interval tree represents an ordered tree data structure to store tag spans in. It
/// allows you to efficiently find all tag spans that intersect a provided span. Tag spans are
/// tracked. That way you can query for intersecting/overlapping spans in a different snapshot
/// than the one for the tag spans that were added.
/// </summary>
internal partial class TagSpanIntervalTree<TTag> where TTag : ITag
{
private readonly IntervalTree<TagNode> _tree;
private readonly ITextBuffer _textBuffer;
private readonly SpanTrackingMode _spanTrackingMode;
public TagSpanIntervalTree(ITextBuffer textBuffer,
SpanTrackingMode trackingMode,
IEnumerable<ITagSpan<TTag>>? values = null)
{
_textBuffer = textBuffer;
_spanTrackingMode = trackingMode;
var nodeValues = values?.Select(ts => new TagNode(ts, trackingMode));
var introspector = new IntervalIntrospector(textBuffer.CurrentSnapshot);
_tree = IntervalTree.Create(introspector, nodeValues);
}
public ITextBuffer Buffer => _textBuffer;
public SpanTrackingMode SpanTrackingMode => _spanTrackingMode;
public IList<ITagSpan<TTag>> GetIntersectingSpans(SnapshotSpan snapshotSpan)
{
var snapshot = snapshotSpan.Snapshot;
Debug.Assert(snapshot.TextBuffer == _textBuffer);
var introspector = new IntervalIntrospector(snapshot);
var intersectingIntervals = _tree.GetIntervalsThatIntersectWith(snapshotSpan.Start, snapshotSpan.Length, introspector);
List<ITagSpan<TTag>>? result = null;
foreach (var tagNode in intersectingIntervals)
{
result ??= new List<ITagSpan<TTag>>();
result.Add(new TagSpan<TTag>(tagNode.Span.GetSpan(snapshot), tagNode.Tag));
}
return result ?? SpecializedCollections.EmptyList<ITagSpan<TTag>>();
}
public IEnumerable<ITagSpan<TTag>> GetSpans(ITextSnapshot snapshot)
=> _tree.Select(tn => new TagSpan<TTag>(tn.Span.GetSpan(snapshot), tn.Tag));
public bool IsEmpty()
=> _tree.IsEmpty();
public IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = GetIntersectingTagSpansWorker(requestedSpans);
DebugVerifyTags(requestedSpans, result);
return result;
}
[Conditional("DEBUG")]
private static void DebugVerifyTags(NormalizedSnapshotSpanCollection requestedSpans, IEnumerable<ITagSpan<TTag>> tags)
{
if (tags == null)
{
return;
}
foreach (var tag in tags)
{
var span = tag.Span;
if (!requestedSpans.Any(s => s.IntersectsWith(span)))
{
Contract.Fail(tag + " doesn't intersects with any requested span");
}
}
}
private IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpansWorker(NormalizedSnapshotSpanCollection requestedSpans)
{
const int MaxNumberOfRequestedSpans = 100;
// Special case the case where there is only one requested span. In that case, we don't
// need to allocate any intermediate collections
return requestedSpans.Count == 1
? GetIntersectingSpans(requestedSpans[0])
: requestedSpans.Count < MaxNumberOfRequestedSpans
? GetTagsForSmallNumberOfSpans(requestedSpans)
: GetTagsForLargeNumberOfSpans(requestedSpans);
}
private IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = new List<ITagSpan<TTag>>();
foreach (var s in requestedSpans)
{
result.AddRange(GetIntersectingSpans(s));
}
return result;
}
private IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
// we are asked with bunch of spans. rather than asking same question again and again, ask once with big span
// which will return superset of what we want. and then filter them out in O(m+n) cost.
// m == number of requested spans, n = number of returned spans
var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End);
var result = GetIntersectingSpans(mergedSpan);
var requestIndex = 0;
var enumerator = result.GetEnumerator();
try
{
if (!enumerator.MoveNext())
{
return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>();
}
var hashSet = new HashSet<ITagSpan<TTag>>();
while (true)
{
var currentTag = enumerator.Current;
var currentRequestSpan = requestedSpans[requestIndex];
var currentTagSpan = currentTag.Span;
if (currentRequestSpan.Start > currentTagSpan.End)
{
if (!enumerator.MoveNext())
{
break;
}
}
else if (currentTagSpan.Start > currentRequestSpan.End)
{
requestIndex++;
if (requestIndex >= requestedSpans.Count)
{
break;
}
}
else
{
if (currentTagSpan.Length > 0)
{
hashSet.Add(currentTag);
}
if (!enumerator.MoveNext())
{
break;
}
}
}
return hashSet;
}
finally
{
enumerator.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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
/// <summary>
/// A tag span interval tree represents an ordered tree data structure to store tag spans in. It
/// allows you to efficiently find all tag spans that intersect a provided span. Tag spans are
/// tracked. That way you can query for intersecting/overlapping spans in a different snapshot
/// than the one for the tag spans that were added.
/// </summary>
internal partial class TagSpanIntervalTree<TTag> where TTag : ITag
{
private readonly IntervalTree<TagNode> _tree;
private readonly ITextBuffer _textBuffer;
private readonly SpanTrackingMode _spanTrackingMode;
public TagSpanIntervalTree(ITextBuffer textBuffer,
SpanTrackingMode trackingMode,
IEnumerable<ITagSpan<TTag>>? values = null)
{
_textBuffer = textBuffer;
_spanTrackingMode = trackingMode;
var nodeValues = values?.Select(ts => new TagNode(ts, trackingMode));
var introspector = new IntervalIntrospector(textBuffer.CurrentSnapshot);
_tree = IntervalTree.Create(introspector, nodeValues);
}
public ITextBuffer Buffer => _textBuffer;
public SpanTrackingMode SpanTrackingMode => _spanTrackingMode;
public IList<ITagSpan<TTag>> GetIntersectingSpans(SnapshotSpan snapshotSpan)
{
var snapshot = snapshotSpan.Snapshot;
Debug.Assert(snapshot.TextBuffer == _textBuffer);
var introspector = new IntervalIntrospector(snapshot);
var intersectingIntervals = _tree.GetIntervalsThatIntersectWith(snapshotSpan.Start, snapshotSpan.Length, introspector);
List<ITagSpan<TTag>>? result = null;
foreach (var tagNode in intersectingIntervals)
{
result ??= new List<ITagSpan<TTag>>();
result.Add(new TagSpan<TTag>(tagNode.Span.GetSpan(snapshot), tagNode.Tag));
}
return result ?? SpecializedCollections.EmptyList<ITagSpan<TTag>>();
}
public IEnumerable<ITagSpan<TTag>> GetSpans(ITextSnapshot snapshot)
=> _tree.Select(tn => new TagSpan<TTag>(tn.Span.GetSpan(snapshot), tn.Tag));
public bool IsEmpty()
=> _tree.IsEmpty();
public IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = GetIntersectingTagSpansWorker(requestedSpans);
DebugVerifyTags(requestedSpans, result);
return result;
}
[Conditional("DEBUG")]
private static void DebugVerifyTags(NormalizedSnapshotSpanCollection requestedSpans, IEnumerable<ITagSpan<TTag>> tags)
{
if (tags == null)
{
return;
}
foreach (var tag in tags)
{
var span = tag.Span;
if (!requestedSpans.Any(s => s.IntersectsWith(span)))
{
Contract.Fail(tag + " doesn't intersects with any requested span");
}
}
}
private IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpansWorker(NormalizedSnapshotSpanCollection requestedSpans)
{
const int MaxNumberOfRequestedSpans = 100;
// Special case the case where there is only one requested span. In that case, we don't
// need to allocate any intermediate collections
return requestedSpans.Count == 1
? GetIntersectingSpans(requestedSpans[0])
: requestedSpans.Count < MaxNumberOfRequestedSpans
? GetTagsForSmallNumberOfSpans(requestedSpans)
: GetTagsForLargeNumberOfSpans(requestedSpans);
}
private IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = new List<ITagSpan<TTag>>();
foreach (var s in requestedSpans)
{
result.AddRange(GetIntersectingSpans(s));
}
return result;
}
private IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
// we are asked with bunch of spans. rather than asking same question again and again, ask once with big span
// which will return superset of what we want. and then filter them out in O(m+n) cost.
// m == number of requested spans, n = number of returned spans
var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End);
var result = GetIntersectingSpans(mergedSpan);
var requestIndex = 0;
var enumerator = result.GetEnumerator();
try
{
if (!enumerator.MoveNext())
{
return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>();
}
var hashSet = new HashSet<ITagSpan<TTag>>();
while (true)
{
var currentTag = enumerator.Current;
var currentRequestSpan = requestedSpans[requestIndex];
var currentTagSpan = currentTag.Span;
if (currentRequestSpan.Start > currentTagSpan.End)
{
if (!enumerator.MoveNext())
{
break;
}
}
else if (currentTagSpan.Start > currentRequestSpan.End)
{
requestIndex++;
if (requestIndex >= requestedSpans.Count)
{
break;
}
}
else
{
if (currentTagSpan.Length > 0)
{
hashSet.Add(currentTag);
}
if (!enumerator.MoveNext())
{
break;
}
}
}
return hashSet;
}
finally
{
enumerator.Dispose();
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundNamespaceExpression.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNamespaceExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol, hasErrors As Boolean)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol)
End Sub
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return If(DirectCast(Me.AliasOpt, Symbol), Me.NamespaceSymbol)
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
If NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Return LookupResult.WorseResultKind(LookupResultKind.Ambiguous, MyBase.ResultKind)
End If
Return MyBase.ResultKind
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnevaluatedReceiverOpt Is Nothing OrElse UnevaluatedReceiverOpt.Kind = BoundKind.NamespaceExpression)
Debug.Assert(AliasOpt Is Nothing OrElse NamespaceSymbol.NamespaceKind <> NamespaceKindNamespaceGroup)
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNamespaceExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol, hasErrors As Boolean)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol)
End Sub
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return If(DirectCast(Me.AliasOpt, Symbol), Me.NamespaceSymbol)
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
If NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Return LookupResult.WorseResultKind(LookupResultKind.Ambiguous, MyBase.ResultKind)
End If
Return MyBase.ResultKind
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnevaluatedReceiverOpt Is Nothing OrElse UnevaluatedReceiverOpt.Kind = BoundKind.NamespaceExpression)
Debug.Assert(AliasOpt Is Nothing OrElse NamespaceSymbol.NamespaceKind <> NamespaceKindNamespaceGroup)
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Def/Implementation/ProjectInfo/DefaultProjectInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.LanguageServices.ProjectInfoService;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectInfoService
{
internal sealed class DefaultProjectInfoService : IProjectInfoService
{
public bool GeneratedTypesMustBePublic(Project project)
{
if (!(project.Solution.Workspace is VisualStudioWorkspaceImpl))
{
return false;
}
// TODO: reimplement
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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices.ProjectInfoService;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectInfoService
{
internal sealed class DefaultProjectInfoService : IProjectInfoService
{
public bool GeneratedTypesMustBePublic(Project project)
{
if (!(project.Solution.Workspace is VisualStudioWorkspaceImpl))
{
return false;
}
// TODO: reimplement
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/SyntaxTokenExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxTokenExtensions
{
public static bool TryParseGenericName(this SyntaxToken genericIdentifier, CancellationToken cancellationToken, [NotNullWhen(true)] out GenericNameSyntax? genericName)
{
if (genericIdentifier.GetNextToken(includeSkipped: true).Kind() == SyntaxKind.LessThanToken)
{
var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName();
var syntaxTree = genericIdentifier.SyntaxTree!;
var name = SyntaxFactory.ParseName(syntaxTree.GetText(cancellationToken).ToString(TextSpan.FromBounds(genericIdentifier.SpanStart, lastToken.Span.End)));
genericName = name as GenericNameSyntax;
return genericName != null;
}
genericName = null;
return false;
}
/// <summary>
/// Lexically, find the last token that looks like it's part of this generic name.
/// </summary>
/// <param name="genericIdentifier">The "name" of the generic identifier, last token before
/// the "&"</param>
/// <returns>The last token in the name</returns>
/// <remarks>This is related to the code in <see cref="SyntaxTreeExtensions.IsInPartiallyWrittenGeneric(SyntaxTree, int, CancellationToken)"/></remarks>
public static SyntaxToken FindLastTokenOfPartialGenericName(this SyntaxToken genericIdentifier)
{
Contract.ThrowIfFalse(genericIdentifier.Kind() == SyntaxKind.IdentifierToken);
// advance to the "<" token
var token = genericIdentifier.GetNextToken(includeSkipped: true);
Contract.ThrowIfFalse(token.Kind() == SyntaxKind.LessThanToken);
var stack = 0;
do
{
// look forward one token
{
var next = token.GetNextToken(includeSkipped: true);
if (next.Kind() == SyntaxKind.None)
{
return token;
}
token = next;
}
if (token.Kind() == SyntaxKind.GreaterThanToken)
{
if (stack == 0)
{
return token;
}
else
{
stack--;
continue;
}
}
switch (token.Kind())
{
case SyntaxKind.LessThanLessThanToken:
stack++;
goto case SyntaxKind.LessThanToken;
// fall through
case SyntaxKind.LessThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
case SyntaxKind.CommaToken:
break;
// If we see a member declaration keyword, we know we've gone too far
case SyntaxKind.ClassKeyword:
case SyntaxKind.StructKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.DelegateKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.VoidKeyword:
return token.GetPreviousToken(includeSkipped: true);
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk. Go back to the token before.
return token.GetPreviousToken(includeSkipped: true);
}
}
while (true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxTokenExtensions
{
public static bool TryParseGenericName(this SyntaxToken genericIdentifier, CancellationToken cancellationToken, [NotNullWhen(true)] out GenericNameSyntax? genericName)
{
if (genericIdentifier.GetNextToken(includeSkipped: true).Kind() == SyntaxKind.LessThanToken)
{
var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName();
var syntaxTree = genericIdentifier.SyntaxTree!;
var name = SyntaxFactory.ParseName(syntaxTree.GetText(cancellationToken).ToString(TextSpan.FromBounds(genericIdentifier.SpanStart, lastToken.Span.End)));
genericName = name as GenericNameSyntax;
return genericName != null;
}
genericName = null;
return false;
}
/// <summary>
/// Lexically, find the last token that looks like it's part of this generic name.
/// </summary>
/// <param name="genericIdentifier">The "name" of the generic identifier, last token before
/// the "&"</param>
/// <returns>The last token in the name</returns>
/// <remarks>This is related to the code in <see cref="SyntaxTreeExtensions.IsInPartiallyWrittenGeneric(SyntaxTree, int, CancellationToken)"/></remarks>
public static SyntaxToken FindLastTokenOfPartialGenericName(this SyntaxToken genericIdentifier)
{
Contract.ThrowIfFalse(genericIdentifier.Kind() == SyntaxKind.IdentifierToken);
// advance to the "<" token
var token = genericIdentifier.GetNextToken(includeSkipped: true);
Contract.ThrowIfFalse(token.Kind() == SyntaxKind.LessThanToken);
var stack = 0;
do
{
// look forward one token
{
var next = token.GetNextToken(includeSkipped: true);
if (next.Kind() == SyntaxKind.None)
{
return token;
}
token = next;
}
if (token.Kind() == SyntaxKind.GreaterThanToken)
{
if (stack == 0)
{
return token;
}
else
{
stack--;
continue;
}
}
switch (token.Kind())
{
case SyntaxKind.LessThanLessThanToken:
stack++;
goto case SyntaxKind.LessThanToken;
// fall through
case SyntaxKind.LessThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
case SyntaxKind.CommaToken:
break;
// If we see a member declaration keyword, we know we've gone too far
case SyntaxKind.ClassKeyword:
case SyntaxKind.StructKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.DelegateKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.VoidKeyword:
return token.GetPreviousToken(includeSkipped: true);
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk. Go back to the token before.
return token.GetPreviousToken(includeSkipped: true);
}
}
while (true);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Test/Progression/ProgressionTestHelpers.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 Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression
Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml">
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Friend Module ProgressionTestHelpers
<Extension>
Public Function ToSimplifiedXDocument(graph As Graph) As XDocument
Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000))
document.Root.<Categories>.Remove()
document.Root.<Properties>.Remove()
document.Root.<QualifiedNames>.Remove()
For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml"))
Dim attribute = node.Attribute("SourceLocation")
If attribute IsNot Nothing Then
attribute.Remove()
End If
Next
Return document
End Function
Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement)
Dim graphXml = graph.ToSimplifiedXDocument()
If Not XNode.DeepEquals(graphXml.Root, xml) Then
' They aren't equal, so therefore the text representations definitely aren't equal.
' We'll Assert.Equal those, so that way xunit will show nice before/after text
'Assert.Equal(xml.ToString(), graphXml.ToString())
' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output
Throw New Exception($"Graph XML was not equal, check for out-of-order elements.
Expected:
{xml.ToString()}
Actual:
{graphXml.ToString()}
")
End If
End Sub
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 Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression
Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml">
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Friend Module ProgressionTestHelpers
<Extension>
Public Function ToSimplifiedXDocument(graph As Graph) As XDocument
Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000))
document.Root.<Categories>.Remove()
document.Root.<Properties>.Remove()
document.Root.<QualifiedNames>.Remove()
For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml"))
Dim attribute = node.Attribute("SourceLocation")
If attribute IsNot Nothing Then
attribute.Remove()
End If
Next
Return document
End Function
Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement)
Dim graphXml = graph.ToSimplifiedXDocument()
If Not XNode.DeepEquals(graphXml.Root, xml) Then
' They aren't equal, so therefore the text representations definitely aren't equal.
' We'll Assert.Equal those, so that way xunit will show nice before/after text
'Assert.Equal(xml.ToString(), graphXml.ToString())
' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output
Throw New Exception($"Graph XML was not equal, check for out-of-order elements.
Expected:
{xml.ToString()}
Actual:
{graphXml.ToString()}
")
End If
End Sub
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseNullPropagation;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation
{
public partial class UseNullPropagationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseNullPropagationTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseNullPropagationDiagnosticAnalyzer(), new CSharpUseNullPropagationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_Equals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnCSharp5()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_Equals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]null == o ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_NotEquals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableType()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c != null ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndObjectCast()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = (object)[||]c != null ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_NotEquals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]null != o ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIndexer()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o[0];
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestConditionalAccess()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B?.C;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B?.C;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMemberAccess()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnSimpleMatch()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedCondition()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll1()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v1 = {|FixAllInDocument:o|} == null ? null : o.ToString();
var v2 = o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v1 = o?.ToString();
var v2 = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll2()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = {|FixAllInDocument:o1|} == null ? null : o1.ToString(o2 == null ? null : o2.ToString());
}
}",
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = o1?.ToString(o2?.ToString());
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? 0 : o.ToString();
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : 0;
}
}");
}
[WorkItem(16287, "https://github.com/dotnet/roslyn/issues/16287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMethodGroup()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class D
{
void Goo()
{
var c = new C();
Action<string> a = [||]c != null ? c.M : (Action<string>)null;
}
}
class C { public void M(string s) { } }");
}
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
void Main(string s)
{
Method<string>(t => [||]s != null ? s.ToString() : null); // works
}
public void Method<T>(Expression<Func<T, string>> functor)
{
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
select [||]item == null ? null : item.Value.x;
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree3()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
where ([||]item == null ? null : item.Value.x) > 0
select item;
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree4()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
let x = [||]item == null ? null : item.Value.x
select x;
}
}");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableMemberAccess()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = [||]toDate == null ? null : toDate.Value.ToString(""yyyy/MM/ dd"");
}
}
",
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = toDate?.ToString(""yyyy/MM/ dd"");
}
}
");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableElementAccess()
{
await TestInRegularAndScript1Async(
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = [||]s == null ? null : s.Value[0];
}
}
",
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = s?[0];
}
}
");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndIsNull()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c is null ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndIsType()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c is C ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIsOtherConstant()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
void M(string s)
{
int? x = [||]s is """" ? null : (int?)s.Length;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEquals1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]ReferenceEquals(c, null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEquals2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]ReferenceEquals(null, c) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValue1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]ReferenceEquals(c, other) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValue2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]ReferenceEquals(other, c) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsWithObject1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]object.ReferenceEquals(c, null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsWithObject2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]object.ReferenceEquals(null, c) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]object.ReferenceEquals(c, other) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]object.ReferenceEquals(other, c) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsNull()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c is null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsType()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c is C) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsOtherConstant()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
void M(string s)
{
int? x = [||]!(s is """") ? (int?)s.Length : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEquals1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!ReferenceEquals(c, null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEquals2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!ReferenceEquals(null, c) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!ReferenceEquals(c, other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!ReferenceEquals(other, c) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!object.ReferenceEquals(c, null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!object.ReferenceEquals(null, c) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!object.ReferenceEquals(c, other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!object.ReferenceEquals(other, c) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestEqualsWithLogicalNot()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c == null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNotEqualsWithLogicalNot()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c != null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestEqualsOtherValueWithLogicalNot()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!(c == other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNotEqualsOtherValueWithLogicalNot()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!(c != other) ? null : c.f;
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedExpression()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : (o.ToString());
}
}",
@"using System;
class C
{
void M(object o)
{
var v = (o?.ToString());
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestReversedParenthesizedExpression()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o != null) ? (o.ToString()) : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = (o?.ToString());
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedNull()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? (null) : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestReversedParenthesizedNull()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : (null);
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseNullPropagation;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation
{
public partial class UseNullPropagationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseNullPropagationTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseNullPropagationDiagnosticAnalyzer(), new CSharpUseNullPropagationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_Equals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnCSharp5()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_Equals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]null == o ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_NotEquals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableType()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c != null ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndObjectCast()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = (object)[||]c != null ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_NotEquals()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]null != o ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIndexer()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o[0];
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestConditionalAccess()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B?.C;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B?.C;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMemberAccess()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnSimpleMatch()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedCondition()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll1()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v1 = {|FixAllInDocument:o|} == null ? null : o.ToString();
var v2 = o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v1 = o?.ToString();
var v2 = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll2()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = {|FixAllInDocument:o1|} == null ? null : o1.ToString(o2 == null ? null : o2.ToString());
}
}",
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = o1?.ToString(o2?.ToString());
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? 0 : o.ToString();
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : 0;
}
}");
}
[WorkItem(16287, "https://github.com/dotnet/roslyn/issues/16287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMethodGroup()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class D
{
void Goo()
{
var c = new C();
Action<string> a = [||]c != null ? c.M : (Action<string>)null;
}
}
class C { public void M(string s) { } }");
}
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
void Main(string s)
{
Method<string>(t => [||]s != null ? s.ToString() : null); // works
}
public void Method<T>(Expression<Func<T, string>> functor)
{
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
select [||]item == null ? null : item.Value.x;
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree3()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
where ([||]item == null ? null : item.Value.x) > 0
select item;
}
}");
}
[WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")]
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree4()
{
await TestMissingInRegularAndScriptAsync(
@"
using System.Linq;
class C
{
void Main()
{
_ = from item in Enumerable.Empty<(int? x, int? y)?>().AsQueryable()
let x = [||]item == null ? null : item.Value.x
select x;
}
}");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableMemberAccess()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = [||]toDate == null ? null : toDate.Value.ToString(""yyyy/MM/ dd"");
}
}
",
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = toDate?.ToString(""yyyy/MM/ dd"");
}
}
");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableElementAccess()
{
await TestInRegularAndScript1Async(
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = [||]s == null ? null : s.Value[0];
}
}
",
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = s?[0];
}
}
");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndIsNull()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c is null ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndIsType()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]c is C ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIsOtherConstant()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
void M(string s)
{
int? x = [||]s is """" ? null : (int?)s.Length;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEquals1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]ReferenceEquals(c, null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEquals2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]ReferenceEquals(null, c) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValue1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]ReferenceEquals(c, other) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValue2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]ReferenceEquals(other, c) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsWithObject1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]object.ReferenceEquals(c, null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsWithObject2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]object.ReferenceEquals(null, c) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]object.ReferenceEquals(c, other) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]object.ReferenceEquals(other, c) ? null : c.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsNull()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c is null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsType()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c is C) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndNotIsOtherConstant()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
void M(string s)
{
int? x = [||]!(s is """") ? (int?)s.Length : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEquals1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!ReferenceEquals(c, null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEquals2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!ReferenceEquals(null, c) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!ReferenceEquals(c, other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!ReferenceEquals(other, c) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!object.ReferenceEquals(c, null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!object.ReferenceEquals(null, c) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!object.ReferenceEquals(c, other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!object.ReferenceEquals(other, c) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestEqualsWithLogicalNot()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c == null) ? c.f : null;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNotEqualsWithLogicalNot()
{
await TestInRegularAndScript1Async(
@"
class C
{
public int? f;
void M(C c)
{
int? x = [||]!(c != null) ? null : c.f;
}
}",
@"
class C
{
public int? f;
void M(C c)
{
int? x = c?.f;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestEqualsOtherValueWithLogicalNot()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!(c == other) ? c.f : null;
}
}");
}
[WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNotEqualsOtherValueWithLogicalNot()
{
await TestMissingInRegularAndScriptAsync(
@"
class C
{
public int? f;
void M(C c, C other)
{
int? x = [||]!(c != other) ? null : c.f;
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedExpression()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : (o.ToString());
}
}",
@"using System;
class C
{
void M(object o)
{
var v = (o?.ToString());
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestReversedParenthesizedExpression()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||](o != null) ? (o.ToString()) : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = (o?.ToString());
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedNull()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? (null) : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[WorkItem(49517, "https://github.com/dotnet/roslyn/issues/49517")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestReversedParenthesizedNull()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : (null);
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/MSBuild/MSBuild/Constants/ItemNames.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.MSBuild
{
internal static class ItemNames
{
public const string AdditionalFiles = nameof(AdditionalFiles);
public const string Analyzer = nameof(Analyzer);
public const string Compile = nameof(Compile);
public const string CscCommandLineArgs = nameof(CscCommandLineArgs);
public const string DocFileItem = nameof(DocFileItem);
public const string EditorConfigFiles = nameof(EditorConfigFiles);
public const string Import = nameof(Import);
public const string ProjectReference = nameof(ProjectReference);
public const string Reference = nameof(Reference);
public const string ReferencePath = nameof(ReferencePath);
public const string VbcCommandLineArgs = nameof(VbcCommandLineArgs);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.MSBuild
{
internal static class ItemNames
{
public const string AdditionalFiles = nameof(AdditionalFiles);
public const string Analyzer = nameof(Analyzer);
public const string Compile = nameof(Compile);
public const string CscCommandLineArgs = nameof(CscCommandLineArgs);
public const string DocFileItem = nameof(DocFileItem);
public const string EditorConfigFiles = nameof(EditorConfigFiles);
public const string Import = nameof(Import);
public const string ProjectReference = nameof(ProjectReference);
public const string Reference = nameof(Reference);
public const string ReferencePath = nameof(ReferencePath);
public const string VbcCommandLineArgs = nameof(VbcCommandLineArgs);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AbstractNativeIntegerKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal abstract class AbstractNativeIntegerKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
{
protected abstract RecommendedKeyword Keyword { get; }
private static bool IsValidContext(CSharpSyntaxContext context)
{
if (context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsPossibleTupleContext ||
context.IsAtStartOfPattern ||
(context.IsTypeContext && !context.IsEnumBaseListContext))
{
return true;
}
return context.IsLocalVariableDeclarationContext;
}
public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> IsValidContext(context) ? ImmutableArray.Create(Keyword) : ImmutableArray<RecommendedKeyword>.Empty;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal abstract class AbstractNativeIntegerKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext>
{
protected abstract RecommendedKeyword Keyword { get; }
private static bool IsValidContext(CSharpSyntaxContext context)
{
if (context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsPossibleTupleContext ||
context.IsAtStartOfPattern ||
(context.IsTypeContext && !context.IsEnumBaseListContext))
{
return true;
}
return context.IsLocalVariableDeclarationContext;
}
public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> IsValidContext(context) ? ImmutableArray.Create(Keyword) : ImmutableArray<RecommendedKeyword>.Empty;
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/ConstKeywordRecommender.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
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Const" keyword for the start of a statement.
''' </summary>
Friend Class ConstKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Const", VBFeaturesResources.Declares_and_defines_one_or_more_constants))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, 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
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Const" keyword for the start of a statement.
''' </summary>
Friend Class ConstKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Const", VBFeaturesResources.Declares_and_defines_one_or_more_constants))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/CSharp/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal sealed class StringLiteralExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<LiteralExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
LiteralExpressionSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node.IsKind(SyntaxKind.StringLiteralExpression) &&
!node.ContainsDiagnostics)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: BlockTypes.Expression,
autoCollapse: true,
isDefaultCollapsed: false));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal sealed class StringLiteralExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<LiteralExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
LiteralExpressionSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node.IsKind(SyntaxKind.StringLiteralExpression) &&
!node.ContainsDiagnostics)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: BlockTypes.Expression,
autoCollapse: true,
isDefaultCollapsed: false));
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged
{
private readonly AnalyzersFolderItem _analyzersFolder;
private readonly IAnalyzersCommandHandler _commandHandler;
private IReadOnlyCollection<AnalyzerReference> _analyzerReferences;
private BulkObservableCollection<AnalyzerItem> _analyzerItems;
public event PropertyChangedEventHandler PropertyChanged;
public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler)
{
_analyzersFolder = analyzersFolder;
_commandHandler = commandHandler;
_analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged;
}
private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
UpdateAnalyzers();
break;
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectChanged:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
UpdateAnalyzers();
}
break;
case WorkspaceChangeKind.ProjectRemoved:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
}
break;
}
}
private void UpdateAnalyzers()
{
if (_analyzerItems == null)
{
// The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems
// may have changed.
NotifyPropertyChanged(nameof(HasItems));
return;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null &&
project.AnalyzerReferences != _analyzerReferences)
{
_analyzerReferences = project.AnalyzerReferences;
_analyzerItems.BeginBulkOperation();
var itemsToRemove = _analyzerItems
.Where(item => !_analyzerReferences.Contains(item.AnalyzerReference))
.ToArray();
var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project)
.Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r))
.ToArray();
foreach (var item in itemsToRemove)
{
_analyzerItems.Remove(item);
}
foreach (var reference in referencesToAdd)
{
_analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController));
}
var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray();
for (var i = 0; i < sorted.Length; i++)
{
_analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i);
}
_analyzerItems.EndBulkOperation();
NotifyPropertyChanged(nameof(HasItems));
}
}
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool HasItems
{
get
{
if (_analyzerItems != null)
{
return _analyzerItems.Count > 0;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
return project.AnalyzerReferences.Count > 0;
}
return false;
}
}
public IEnumerable Items
{
get
{
if (_analyzerItems == null)
{
_analyzerItems = new BulkObservableCollection<AnalyzerItem>();
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
_analyzerReferences = project.AnalyzerReferences;
var initialSet = GetFilteredAnalyzers(_analyzerReferences, project)
.OrderBy(ar => ar.Display)
.Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController));
_analyzerItems.AddRange(initialSet);
}
}
Logger.Log(
FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems,
KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count));
return _analyzerItems;
}
}
public object SourceItem
{
get
{
return _analyzersFolder;
}
}
private ImmutableHashSet<string> GetAnalyzersWithLoadErrors()
{
if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl)
{
/*
var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId);
var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap();
if (vsAnalyzersMap != null)
{
return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet();
}
*/
}
return ImmutableHashSet<string>.Empty;
}
private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project)
{
var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors();
// Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors.
var builder = ArrayBuilder<AnalyzerReference>.GetInstance();
foreach (var analyzerReference in analyzerReferences)
{
// Analyzer dependency:
// 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies).
// 2. Mush have no diagnostic analyzers.
// 3. Must have no source generators.
// 4. Must have non-null full path.
// 5. Must not have any assembly or analyzer load failures.
if (analyzerReference is AnalyzerFileReference &&
analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty &&
analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty &&
analyzerReference.FullPath != null &&
!analyzersWithLoadErrors.Contains(analyzerReference.FullPath))
{
continue;
}
builder.Add(analyzerReference);
}
return builder.ToImmutableAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged
{
private readonly AnalyzersFolderItem _analyzersFolder;
private readonly IAnalyzersCommandHandler _commandHandler;
private IReadOnlyCollection<AnalyzerReference> _analyzerReferences;
private BulkObservableCollection<AnalyzerItem> _analyzerItems;
public event PropertyChangedEventHandler PropertyChanged;
public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler)
{
_analyzersFolder = analyzersFolder;
_commandHandler = commandHandler;
_analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged;
}
private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
UpdateAnalyzers();
break;
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectChanged:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
UpdateAnalyzers();
}
break;
case WorkspaceChangeKind.ProjectRemoved:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
}
break;
}
}
private void UpdateAnalyzers()
{
if (_analyzerItems == null)
{
// The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems
// may have changed.
NotifyPropertyChanged(nameof(HasItems));
return;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null &&
project.AnalyzerReferences != _analyzerReferences)
{
_analyzerReferences = project.AnalyzerReferences;
_analyzerItems.BeginBulkOperation();
var itemsToRemove = _analyzerItems
.Where(item => !_analyzerReferences.Contains(item.AnalyzerReference))
.ToArray();
var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project)
.Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r))
.ToArray();
foreach (var item in itemsToRemove)
{
_analyzerItems.Remove(item);
}
foreach (var reference in referencesToAdd)
{
_analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController));
}
var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray();
for (var i = 0; i < sorted.Length; i++)
{
_analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i);
}
_analyzerItems.EndBulkOperation();
NotifyPropertyChanged(nameof(HasItems));
}
}
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool HasItems
{
get
{
if (_analyzerItems != null)
{
return _analyzerItems.Count > 0;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
return project.AnalyzerReferences.Count > 0;
}
return false;
}
}
public IEnumerable Items
{
get
{
if (_analyzerItems == null)
{
_analyzerItems = new BulkObservableCollection<AnalyzerItem>();
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
_analyzerReferences = project.AnalyzerReferences;
var initialSet = GetFilteredAnalyzers(_analyzerReferences, project)
.OrderBy(ar => ar.Display)
.Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController));
_analyzerItems.AddRange(initialSet);
}
}
Logger.Log(
FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems,
KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count));
return _analyzerItems;
}
}
public object SourceItem
{
get
{
return _analyzersFolder;
}
}
private ImmutableHashSet<string> GetAnalyzersWithLoadErrors()
{
if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl)
{
/*
var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId);
var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap();
if (vsAnalyzersMap != null)
{
return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet();
}
*/
}
return ImmutableHashSet<string>.Empty;
}
private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project)
{
var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors();
// Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors.
var builder = ArrayBuilder<AnalyzerReference>.GetInstance();
foreach (var analyzerReference in analyzerReferences)
{
// Analyzer dependency:
// 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies).
// 2. Mush have no diagnostic analyzers.
// 3. Must have no source generators.
// 4. Must have non-null full path.
// 5. Must not have any assembly or analyzer load failures.
if (analyzerReference is AnalyzerFileReference &&
analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty &&
analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty &&
analyzerReference.FullPath != null &&
!analyzersWithLoadErrors.Contains(analyzerReference.FullPath))
{
continue;
}
builder.Add(analyzerReference);
}
return builder.ToImmutableAndFree();
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using Xunit;
#pragma warning disable IDE0039 // Use local function
namespace Microsoft.CodeAnalysis.UnitTests
{
[SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")]
public class SpecializedTasksTests
{
private record StateType;
private record IntermediateType;
private record ResultType;
[Fact]
public void WhenAll_Null()
{
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void WhenAll_Empty()
{
var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>());
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Same(Array.Empty<int>(), whenAll.Result);
}
[Fact]
public void WhenAll_AllCompletedSuccessfully()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) });
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Equal(new[] { 0, 1 }, whenAll.Result);
}
[Fact]
public void WhenAll_CompletedButCanceled()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) });
Assert.True(whenAll.IsCompleted);
Assert.False(whenAll.IsCompletedSuccessfully);
Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll);
}
[Fact]
public void WhenAll_NotYetCompleted()
{
var completionSource = new TaskCompletionSource<int>();
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) });
Assert.False(whenAll.IsCompleted);
completionSource.SetResult(0);
Assert.True(whenAll.IsCompleted);
Debug.Assert(whenAll.IsCompleted);
Assert.Equal(new[] { 0 }, whenAll.Result);
}
[Fact]
public void Transform_ArgumentValidation()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken));
Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void Transform_SyncCompletedFunction_CompletedTransform()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCompletedSuccessfully);
Assert.NotNull(task.Result);
}
[Fact]
public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CompletedTransform()
{
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
Assert.NotNull(await task);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
cts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsFaulted);
var exception = Assert.Throws<InvalidOperationException>(() => task.Result);
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask());
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using Xunit;
#pragma warning disable IDE0039 // Use local function
namespace Microsoft.CodeAnalysis.UnitTests
{
[SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")]
public class SpecializedTasksTests
{
private record StateType;
private record IntermediateType;
private record ResultType;
[Fact]
public void WhenAll_Null()
{
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void WhenAll_Empty()
{
var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>());
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Same(Array.Empty<int>(), whenAll.Result);
}
[Fact]
public void WhenAll_AllCompletedSuccessfully()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) });
Debug.Assert(whenAll.IsCompleted);
Assert.True(whenAll.IsCompletedSuccessfully);
Assert.Equal(new[] { 0, 1 }, whenAll.Result);
}
[Fact]
public void WhenAll_CompletedButCanceled()
{
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) });
Assert.True(whenAll.IsCompleted);
Assert.False(whenAll.IsCompletedSuccessfully);
Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll);
}
[Fact]
public void WhenAll_NotYetCompleted()
{
var completionSource = new TaskCompletionSource<int>();
var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) });
Assert.False(whenAll.IsCompleted);
completionSource.SetResult(0);
Assert.True(whenAll.IsCompleted);
Debug.Assert(whenAll.IsCompleted);
Assert.Equal(new[] { 0 }, whenAll.Result);
}
[Fact]
public void Transform_ArgumentValidation()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken));
Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
}
[Fact]
public void Transform_SyncCompletedFunction_CompletedTransform()
{
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCompletedSuccessfully);
Assert.NotNull(task.Result);
}
[Fact]
public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CompletedTransform()
{
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => new();
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
Assert.NotNull(await task);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
cts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform()
{
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
// ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the
// cancellation token applied when the intermediate task was cancelled.
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
using var unexpectedCts = new CancellationTokenSource();
unexpectedCts.Cancel();
var executedTransform = false;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
unexpectedCts.Token.ThrowIfCancellationRequested();
throw ExceptionUtilities.Unreachable;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task);
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsFaulted);
var exception = Assert.Throws<InvalidOperationException>(() => task.Result);
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_IgnoresTransform()
{
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = new CancellationToken(canceled: false);
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault;
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault));
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.True(task.IsCanceled);
var exception = Assert.Throws<TaskCanceledException>(() => task.Result);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var executedTransform = false;
var fault = ExceptionUtilities.Unreachable;
var cancellationToken = cts.Token;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
throw fault;
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) =>
{
executedTransform = true;
return new ResultType();
};
var arg = new StateType();
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask());
Assert.True(task.IsCanceled);
Assert.Equal(cancellationToken, exception.CancellationToken);
Assert.False(executedTransform);
}
[Fact]
public void Transform_SyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType());
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
#pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created)
var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken));
#pragma warning restore CA2012 // Use ValueTasks correctly
Assert.Same(fault, exception);
}
[Fact]
public async Task Transform_AsyncCompletedFunction_FaultedTransform()
{
var fault = ExceptionUtilities.Unreachable;
var gate = new ManualResetEventSlim();
Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) =>
{
await Task.Yield();
gate.Wait(CancellationToken.None);
return new IntermediateType();
};
Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault;
var arg = new StateType();
var cancellationToken = new CancellationToken(canceled: false);
var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve();
Assert.False(task.IsCompleted);
gate.Set();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask());
Assert.Same(fault, exception);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Remote/ServiceHub/Services/ProcessTelemetry/RemoteProcessTelemetryService.PerformanceReporter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Remote.Diagnostics;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.Telemetry;
using RoslynLogger = Microsoft.CodeAnalysis.Internal.Log.Logger;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class RemoteProcessTelemetryService
{
/// <summary>
/// Track when last time report has sent and send new report if there is update after given internal
/// </summary>
private class PerformanceReporter : GlobalOperationAwareIdleProcessor
{
private readonly SemaphoreSlim _event;
private readonly HashSet<string> _reported;
private readonly IPerformanceTrackerService _diagnosticAnalyzerPerformanceTracker;
private readonly TraceSource _logger;
private readonly TelemetrySession _telemetrySession;
public PerformanceReporter(
TraceSource logger,
TelemetrySession telemetrySession,
IPerformanceTrackerService diagnosticAnalyzerPerformanceTracker,
IGlobalOperationNotificationService globalOperationNotificationService,
CancellationToken shutdownToken)
: base(
AsynchronousOperationListenerProvider.NullListener,
globalOperationNotificationService,
backOffTimeSpan: TimeSpan.FromMinutes(2),
shutdownToken)
{
_event = new SemaphoreSlim(initialCount: 0);
_reported = new HashSet<string>();
_logger = logger;
_telemetrySession = telemetrySession;
_diagnosticAnalyzerPerformanceTracker = diagnosticAnalyzerPerformanceTracker;
_diagnosticAnalyzerPerformanceTracker.SnapshotAdded += OnSnapshotAdded;
Start();
}
protected override void PauseOnGlobalOperation()
{
// we won't cancel report already running. we will just prevent
// new one from starting.
}
protected override async Task ExecuteAsync()
{
// wait for global operation such as build
await GlobalOperationTask.ConfigureAwait(false);
using (var pooledObject = SharedPools.Default<List<ExpensiveAnalyzerInfo>>().GetPooledObject())
using (RoslynLogger.LogBlock(FunctionId.Diagnostics_GeneratePerformaceReport, CancellationToken))
{
_diagnosticAnalyzerPerformanceTracker.GenerateReport(pooledObject.Object);
foreach (var analyzerInfo in pooledObject.Object)
{
var newAnalyzer = _reported.Add(analyzerInfo.AnalyzerId);
var isInternalUser = _telemetrySession.IsUserMicrosoftInternal;
// we only report same analyzer once unless it is internal user
if (isInternalUser || newAnalyzer)
{
// this will report telemetry under VS. this will let us see how accurate our performance tracking is
RoslynLogger.Log(FunctionId.Diagnostics_BadAnalyzer, KeyValueLogMessage.Create(m =>
{
// since it is telemetry, we hash analyzer name if it is not builtin analyzer
m[nameof(analyzerInfo.AnalyzerId)] = isInternalUser ? analyzerInfo.AnalyzerId : analyzerInfo.PIISafeAnalyzerId;
m[nameof(analyzerInfo.LocalOutlierFactor)] = analyzerInfo.LocalOutlierFactor;
m[nameof(analyzerInfo.Average)] = analyzerInfo.Average;
m[nameof(analyzerInfo.AdjustedStandardDeviation)] = analyzerInfo.AdjustedStandardDeviation;
}));
}
// for logging, we only log once. we log here so that we can ask users to provide this log to us
// when we want to find out VS performance issue that could be caused by analyzer
if (newAnalyzer)
{
_logger.TraceEvent(TraceEventType.Warning, 0,
$"Analyzer perf indicators exceeded threshold for '{analyzerInfo.AnalyzerId}' ({analyzerInfo.AnalyzerIdHash}): " +
$"LOF: {analyzerInfo.LocalOutlierFactor}, Avg: {analyzerInfo.Average}, Stddev: {analyzerInfo.AdjustedStandardDeviation}");
}
}
}
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _event.WaitAsync(cancellationToken);
}
private void OnSnapshotAdded(object sender, EventArgs e)
{
// this acts like Monitor.Pulse. (wake up event if it is currently waiting
// if not, ignore. this can have race, but that's fine for this usage case)
// not using Monitor.Pulse since that doesn't support WaitAsync
if (_event.CurrentCount > 0)
{
return;
}
_event.Release();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Remote.Diagnostics;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.Telemetry;
using RoslynLogger = Microsoft.CodeAnalysis.Internal.Log.Logger;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class RemoteProcessTelemetryService
{
/// <summary>
/// Track when last time report has sent and send new report if there is update after given internal
/// </summary>
private class PerformanceReporter : GlobalOperationAwareIdleProcessor
{
private readonly SemaphoreSlim _event;
private readonly HashSet<string> _reported;
private readonly IPerformanceTrackerService _diagnosticAnalyzerPerformanceTracker;
private readonly TraceSource _logger;
private readonly TelemetrySession _telemetrySession;
public PerformanceReporter(
TraceSource logger,
TelemetrySession telemetrySession,
IPerformanceTrackerService diagnosticAnalyzerPerformanceTracker,
IGlobalOperationNotificationService globalOperationNotificationService,
CancellationToken shutdownToken)
: base(
AsynchronousOperationListenerProvider.NullListener,
globalOperationNotificationService,
backOffTimeSpan: TimeSpan.FromMinutes(2),
shutdownToken)
{
_event = new SemaphoreSlim(initialCount: 0);
_reported = new HashSet<string>();
_logger = logger;
_telemetrySession = telemetrySession;
_diagnosticAnalyzerPerformanceTracker = diagnosticAnalyzerPerformanceTracker;
_diagnosticAnalyzerPerformanceTracker.SnapshotAdded += OnSnapshotAdded;
Start();
}
protected override void PauseOnGlobalOperation()
{
// we won't cancel report already running. we will just prevent
// new one from starting.
}
protected override async Task ExecuteAsync()
{
// wait for global operation such as build
await GlobalOperationTask.ConfigureAwait(false);
using (var pooledObject = SharedPools.Default<List<ExpensiveAnalyzerInfo>>().GetPooledObject())
using (RoslynLogger.LogBlock(FunctionId.Diagnostics_GeneratePerformaceReport, CancellationToken))
{
_diagnosticAnalyzerPerformanceTracker.GenerateReport(pooledObject.Object);
foreach (var analyzerInfo in pooledObject.Object)
{
var newAnalyzer = _reported.Add(analyzerInfo.AnalyzerId);
var isInternalUser = _telemetrySession.IsUserMicrosoftInternal;
// we only report same analyzer once unless it is internal user
if (isInternalUser || newAnalyzer)
{
// this will report telemetry under VS. this will let us see how accurate our performance tracking is
RoslynLogger.Log(FunctionId.Diagnostics_BadAnalyzer, KeyValueLogMessage.Create(m =>
{
// since it is telemetry, we hash analyzer name if it is not builtin analyzer
m[nameof(analyzerInfo.AnalyzerId)] = isInternalUser ? analyzerInfo.AnalyzerId : analyzerInfo.PIISafeAnalyzerId;
m[nameof(analyzerInfo.LocalOutlierFactor)] = analyzerInfo.LocalOutlierFactor;
m[nameof(analyzerInfo.Average)] = analyzerInfo.Average;
m[nameof(analyzerInfo.AdjustedStandardDeviation)] = analyzerInfo.AdjustedStandardDeviation;
}));
}
// for logging, we only log once. we log here so that we can ask users to provide this log to us
// when we want to find out VS performance issue that could be caused by analyzer
if (newAnalyzer)
{
_logger.TraceEvent(TraceEventType.Warning, 0,
$"Analyzer perf indicators exceeded threshold for '{analyzerInfo.AnalyzerId}' ({analyzerInfo.AnalyzerIdHash}): " +
$"LOF: {analyzerInfo.LocalOutlierFactor}, Avg: {analyzerInfo.Average}, Stddev: {analyzerInfo.AdjustedStandardDeviation}");
}
}
}
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _event.WaitAsync(cancellationToken);
}
private void OnSnapshotAdded(object sender, EventArgs e)
{
// this acts like Monitor.Pulse. (wake up event if it is currently waiting
// if not, ignore. this can have race, but that's fine for this usage case)
// not using Monitor.Pulse since that doesn't support WaitAsync
if (_event.CurrentCount > 0)
{
return;
}
_event.Release();
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/NavigateTo/NavigateToUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal static class NavigateToUtilities
{
public static ImmutableHashSet<string> GetKindsProvided(Solution solution)
{
var result = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);
foreach (var project in solution.Projects)
{
var navigateToSearchService = project.GetLanguageService<INavigateToSearchService>();
if (navigateToSearchService != null)
result.UnionWith(navigateToSearchService.KindsProvided);
}
return result.ToImmutable();
}
public static TextSpan GetBoundedSpan(INavigableItem item, SourceText sourceText)
{
var spanStart = item.SourceSpan.Start;
var spanEnd = item.SourceSpan.End;
if (item.IsStale)
{
// in the case of a stale item, the span may be out of bounds of the document. Cap
// us to the end of the document as that's where we're going to navigate the user
// to.
spanStart = spanStart > sourceText.Length ? sourceText.Length : spanStart;
spanEnd = spanEnd > sourceText.Length ? sourceText.Length : spanEnd;
}
return TextSpan.FromBounds(spanStart, spanEnd);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal static class NavigateToUtilities
{
public static ImmutableHashSet<string> GetKindsProvided(Solution solution)
{
var result = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);
foreach (var project in solution.Projects)
{
var navigateToSearchService = project.GetLanguageService<INavigateToSearchService>();
if (navigateToSearchService != null)
result.UnionWith(navigateToSearchService.KindsProvided);
}
return result.ToImmutable();
}
public static TextSpan GetBoundedSpan(INavigableItem item, SourceText sourceText)
{
var spanStart = item.SourceSpan.Start;
var spanEnd = item.SourceSpan.End;
if (item.IsStale)
{
// in the case of a stale item, the span may be out of bounds of the document. Cap
// us to the end of the document as that's where we're going to navigate the user
// to.
spanStart = spanStart > sourceText.Length ? sourceText.Length : spanStart;
spanEnd = spanEnd > sourceText.Length ? sourceText.Length : spanEnd;
}
return TextSpan.FromBounds(spanStart, spanEnd);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Portable/Compilation/CSharpCompilerDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Diagnostics.CSharp
{
/// <summary>
/// DiagnosticAnalyzer for C# compiler's syntax/semantic/compilation diagnostics.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpCompilerDiagnosticAnalyzer : CompilerDiagnosticAnalyzer
{
internal override CommonMessageProvider MessageProvider
{
get
{
return CodeAnalysis.CSharp.MessageProvider.Instance;
}
}
internal override ImmutableArray<int> GetSupportedErrorCodes()
{
var errorCodes = Enum.GetValues(typeof(ErrorCode));
var builder = ImmutableArray.CreateBuilder<int>(errorCodes.Length);
foreach (int errorCode in errorCodes)
{
switch (errorCode)
{
case InternalErrorCode.Void:
case InternalErrorCode.Unknown:
continue;
case (int)ErrorCode.WRN_ALinkWarn:
// We don't support configuring WRN_ALinkWarn. See comments in method "CSharpDiagnosticFilter.Filter" for more details.
continue;
case (int)ErrorCode.WRN_UnreferencedField:
case (int)ErrorCode.WRN_UnreferencedFieldAssg:
case (int)ErrorCode.WRN_UnreferencedEvent:
case (int)ErrorCode.WRN_UnassignedInternalField:
// unused field. current live error doesn't support this.
continue;
case (int)ErrorCode.ERR_MissingPredefinedMember:
case (int)ErrorCode.ERR_PredefinedTypeNotFound:
// make it build only error.
continue;
case (int)ErrorCode.ERR_NoEntryPoint:
case (int)ErrorCode.WRN_InvalidMainSig:
case (int)ErrorCode.ERR_MultipleEntryPoints:
case (int)ErrorCode.WRN_MainIgnored:
case (int)ErrorCode.ERR_MainClassNotClass:
case (int)ErrorCode.WRN_MainCantBeGeneric:
case (int)ErrorCode.ERR_NoMainInClass:
case (int)ErrorCode.ERR_MainClassNotFound:
case (int)ErrorCode.WRN_SyncAndAsyncEntryPoints:
// no entry point related errors are live
continue;
case (int)ErrorCode.ERR_BadDelegateConstructor:
case (int)ErrorCode.ERR_InsufficientStack:
case (int)ErrorCode.ERR_ModuleEmitFailure:
case (int)ErrorCode.ERR_TooManyLocals:
case (int)ErrorCode.ERR_BindToBogus:
case (int)ErrorCode.ERR_ExportedTypeConflictsWithDeclaration:
case (int)ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration:
case (int)ErrorCode.ERR_ExportedTypesConflict:
case (int)ErrorCode.ERR_ForwardedTypeConflictsWithExportedType:
case (int)ErrorCode.ERR_ByRefTypeAndAwait:
case (int)ErrorCode.ERR_RefReturningCallAndAwait:
case (int)ErrorCode.ERR_SpecialByRefInLambda:
case (int)ErrorCode.ERR_DynamicRequiredTypesMissing:
// known build only errors which GetDiagnostics doesn't produce
continue;
default:
builder.Add(errorCode);
break;
}
}
return builder.ToImmutable();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Diagnostics.CSharp
{
/// <summary>
/// DiagnosticAnalyzer for C# compiler's syntax/semantic/compilation diagnostics.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpCompilerDiagnosticAnalyzer : CompilerDiagnosticAnalyzer
{
internal override CommonMessageProvider MessageProvider
{
get
{
return CodeAnalysis.CSharp.MessageProvider.Instance;
}
}
internal override ImmutableArray<int> GetSupportedErrorCodes()
{
var errorCodes = Enum.GetValues(typeof(ErrorCode));
var builder = ImmutableArray.CreateBuilder<int>(errorCodes.Length);
foreach (int errorCode in errorCodes)
{
switch (errorCode)
{
case InternalErrorCode.Void:
case InternalErrorCode.Unknown:
continue;
case (int)ErrorCode.WRN_ALinkWarn:
// We don't support configuring WRN_ALinkWarn. See comments in method "CSharpDiagnosticFilter.Filter" for more details.
continue;
case (int)ErrorCode.WRN_UnreferencedField:
case (int)ErrorCode.WRN_UnreferencedFieldAssg:
case (int)ErrorCode.WRN_UnreferencedEvent:
case (int)ErrorCode.WRN_UnassignedInternalField:
// unused field. current live error doesn't support this.
continue;
case (int)ErrorCode.ERR_MissingPredefinedMember:
case (int)ErrorCode.ERR_PredefinedTypeNotFound:
// make it build only error.
continue;
case (int)ErrorCode.ERR_NoEntryPoint:
case (int)ErrorCode.WRN_InvalidMainSig:
case (int)ErrorCode.ERR_MultipleEntryPoints:
case (int)ErrorCode.WRN_MainIgnored:
case (int)ErrorCode.ERR_MainClassNotClass:
case (int)ErrorCode.WRN_MainCantBeGeneric:
case (int)ErrorCode.ERR_NoMainInClass:
case (int)ErrorCode.ERR_MainClassNotFound:
case (int)ErrorCode.WRN_SyncAndAsyncEntryPoints:
// no entry point related errors are live
continue;
case (int)ErrorCode.ERR_BadDelegateConstructor:
case (int)ErrorCode.ERR_InsufficientStack:
case (int)ErrorCode.ERR_ModuleEmitFailure:
case (int)ErrorCode.ERR_TooManyLocals:
case (int)ErrorCode.ERR_BindToBogus:
case (int)ErrorCode.ERR_ExportedTypeConflictsWithDeclaration:
case (int)ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration:
case (int)ErrorCode.ERR_ExportedTypesConflict:
case (int)ErrorCode.ERR_ForwardedTypeConflictsWithExportedType:
case (int)ErrorCode.ERR_ByRefTypeAndAwait:
case (int)ErrorCode.ERR_RefReturningCallAndAwait:
case (int)ErrorCode.ERR_SpecialByRefInLambda:
case (int)ErrorCode.ERR_DynamicRequiredTypesMissing:
// known build only errors which GetDiagnostics doesn't produce
continue;
default:
builder.Add(errorCode);
break;
}
}
return builder.ToImmutable();
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal class RenameTrackingTag : TextMarkerTag
{
internal const string TagId = "RenameTrackingTag";
public static readonly RenameTrackingTag Instance = new();
private RenameTrackingTag()
: base(TagId)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal class RenameTrackingTag : TextMarkerTag
{
internal const string TagId = "RenameTrackingTag";
public static readonly RenameTrackingTag Instance = new();
private RenameTrackingTag()
: base(TagId)
{
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.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.Formatting
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Partial Friend Class VisualBasicTriviaFormatter
Inherits AbstractTriviaFormatter
Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_")
Private _newLine As SyntaxTrivia
Private _succeeded As Boolean = True
Public Sub New(context As FormattingContext,
formattingRules As ChainedFormattingRules,
token1 As SyntaxToken,
token2 As SyntaxToken,
originalString As String,
lineBreaks As Integer,
spaces As Integer)
MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces)
End Sub
Protected Overrides Function Succeeded() As Boolean
Return _succeeded
End Function
Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean
Return trivia.RawKind = SyntaxKind.WhitespaceTrivia
End Function
Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean
Return trivia.RawKind = SyntaxKind.EndOfLineTrivia
End Function
Protected Overrides Function IsWhitespace(ch As Char) As Boolean
Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch)
End Function
Protected Overrides Function IsNewLine(ch As Char) As Boolean
Return SyntaxFacts.IsNewLine(ch)
End Function
Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia
Return SyntaxFactory.Whitespace(text)
End Function
Protected Overrides Function CreateEndOfLine() As SyntaxTrivia
If _newLine = Nothing Then
Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine)
_newLine = SyntaxFactory.EndOfLine(text)
End If
Return _newLine
End Function
Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule
' line continuation
If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then
Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1)
End If
If IsStartOrEndOfFile(trivia1, trivia2) Then
Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0)
End If
' :: case
If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso
trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)
End If
' : after : token
If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)
End If
' : [token]
If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso
Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)
End If
If trivia1.Kind = SyntaxKind.ColonTrivia OrElse
trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)
End If
' [trivia] [whitespace] [token] case
If trivia2.Kind = SyntaxKind.None Then
Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing
If insertNewLine Then
Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)
End If
Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)
End If
' preprocessor case
If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then
' if this is the first line of the file, don't put extra line 1
Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None)
Dim lines = If(firstLine, 0, 1)
Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0)
End If
' comment before a Case Statement case
If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso
Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then
Return LineColumnRule.Preserve
End If
' comment case
If trivia2.Kind = SyntaxKind.CommentTrivia OrElse
trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then
' [token] [whitespace] [trivia] case
If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then
Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)
End If
If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then
Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)
End If
If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then
Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)
End If
Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)
End If
' skipped tokens
If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then
_succeeded = False
End If
Return LineColumnRule.Preserve
End Function
Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean
Return False
End Function
Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean
Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0)
End Function
Protected Overloads Overrides Function Format(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of SyntaxTrivia),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.HasStructure Then
Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)
End If
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
trivia = FormatLineContinuationTrivia(trivia)
End If
changes.Add(trivia)
Return GetLineColumnDelta(lineColumn, trivia)
End Function
Protected Overloads Overrides Function Format(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of TextChange),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.HasStructure Then
Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)
End If
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Dim lineContinuation = FormatLineContinuationTrivia(trivia)
If trivia <> lineContinuation Then
changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString()))
End If
Return GetLineColumnDelta(lineColumn, lineContinuation)
End If
Return GetLineColumnDelta(lineColumn, trivia)
End Function
Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then
Return _lineContinuationTrivia
End If
Return trivia
End Function
Private Function FormatStructuredTrivia(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of SyntaxTrivia),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then
' don't touch anything if it contains skipped tokens
_succeeded = False
changes.Add(trivia)
Return GetLineColumnDelta(lineColumn, trivia)
End If
' TODO : make document comment to be formatted by structured trivia formatter as well.
If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)
Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))
changes.Add(formattedTrivia)
Return GetLineColumnDelta(lineColumn, formattedTrivia)
End If
Dim docComment = FormatDocumentComment(lineColumn, trivia)
changes.Add(docComment)
Return GetLineColumnDelta(lineColumn, docComment)
End Function
Private Function FormatStructuredTrivia(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of TextChange),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then
' don't touch anything if it contains skipped tokens
_succeeded = False
Return GetLineColumnDelta(lineColumn, trivia)
End If
' TODO : make document comment to be formatted by structured trivia formatter as well.
If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(
trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)
If result.GetTextChanges(cancellationToken).Count = 0 Then
Return GetLineColumnDelta(lineColumn, trivia)
End If
changes.AddRange(result.GetTextChanges(cancellationToken))
Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))
Return GetLineColumnDelta(lineColumn, formattedTrivia)
End If
Dim docComment = FormatDocumentComment(lineColumn, trivia)
If docComment <> trivia Then
changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString()))
End If
Return GetLineColumnDelta(lineColumn, docComment)
End Function
Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia
Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart)
Dim text = trivia.ToFullString()
' When the doc comment is parsed from source, even if it is only one
' line long, the end-of-line will get included into the trivia text.
' If the doc comment was parsed from a text fragment, there may not be
' an end-of-line at all. We need to trim the end before we check the
' number of line breaks in the text.
#If NETCOREAPP Then
Dim textWithoutFinalNewLine = text.TrimEnd()
#Else
Dim textWithoutFinalNewLine = text.TrimEnd(Nothing)
#End If
If Not textWithoutFinalNewLine.ContainsLineBreak() Then
Return trivia
End If
Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment(
forceIndentation:=True,
indentation:=indentation,
indentationDelta:=0,
useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs),
tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize),
newLine:=Me.Options.GetOption(FormattingOptions2.NewLine))
If text = singlelineDocComments Then
Return trivia
End If
Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments)
Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1)
Return singlelineDocCommentTrivia.ElementAt(0)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Partial Friend Class VisualBasicTriviaFormatter
Inherits AbstractTriviaFormatter
Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_")
Private _newLine As SyntaxTrivia
Private _succeeded As Boolean = True
Public Sub New(context As FormattingContext,
formattingRules As ChainedFormattingRules,
token1 As SyntaxToken,
token2 As SyntaxToken,
originalString As String,
lineBreaks As Integer,
spaces As Integer)
MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces)
End Sub
Protected Overrides Function Succeeded() As Boolean
Return _succeeded
End Function
Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean
Return trivia.RawKind = SyntaxKind.WhitespaceTrivia
End Function
Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean
Return trivia.RawKind = SyntaxKind.EndOfLineTrivia
End Function
Protected Overrides Function IsWhitespace(ch As Char) As Boolean
Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch)
End Function
Protected Overrides Function IsNewLine(ch As Char) As Boolean
Return SyntaxFacts.IsNewLine(ch)
End Function
Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia
Return SyntaxFactory.Whitespace(text)
End Function
Protected Overrides Function CreateEndOfLine() As SyntaxTrivia
If _newLine = Nothing Then
Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine)
_newLine = SyntaxFactory.EndOfLine(text)
End If
Return _newLine
End Function
Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule
' line continuation
If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then
Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1)
End If
If IsStartOrEndOfFile(trivia1, trivia2) Then
Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0)
End If
' :: case
If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso
trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)
End If
' : after : token
If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0)
End If
' : [token]
If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso
Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)
End If
If trivia1.Kind = SyntaxKind.ColonTrivia OrElse
trivia2.Kind = SyntaxKind.ColonTrivia Then
Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1)
End If
' [trivia] [whitespace] [token] case
If trivia2.Kind = SyntaxKind.None Then
Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing
If insertNewLine Then
Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)
End If
Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)
End If
' preprocessor case
If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then
' if this is the first line of the file, don't put extra line 1
Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None)
Dim lines = If(firstLine, 0, 1)
Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0)
End If
' comment before a Case Statement case
If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso
Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then
Return LineColumnRule.Preserve
End If
' comment case
If trivia2.Kind = SyntaxKind.CommentTrivia OrElse
trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then
' [token] [whitespace] [trivia] case
If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then
Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)
End If
If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then
Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1)
End If
If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then
Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0)
End If
Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0)
End If
' skipped tokens
If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then
_succeeded = False
End If
Return LineColumnRule.Preserve
End Function
Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean
Return False
End Function
Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean
Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0)
End Function
Protected Overloads Overrides Function Format(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of SyntaxTrivia),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.HasStructure Then
Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)
End If
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
trivia = FormatLineContinuationTrivia(trivia)
End If
changes.Add(trivia)
Return GetLineColumnDelta(lineColumn, trivia)
End Function
Protected Overloads Overrides Function Format(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of TextChange),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.HasStructure Then
Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken)
End If
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Dim lineContinuation = FormatLineContinuationTrivia(trivia)
If trivia <> lineContinuation Then
changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString()))
End If
Return GetLineColumnDelta(lineColumn, lineContinuation)
End If
Return GetLineColumnDelta(lineColumn, trivia)
End Function
Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then
Return _lineContinuationTrivia
End If
Return trivia
End Function
Private Function FormatStructuredTrivia(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of SyntaxTrivia),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then
' don't touch anything if it contains skipped tokens
_succeeded = False
changes.Add(trivia)
Return GetLineColumnDelta(lineColumn, trivia)
End If
' TODO : make document comment to be formatted by structured trivia formatter as well.
If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)
Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))
changes.Add(formattedTrivia)
Return GetLineColumnDelta(lineColumn, formattedTrivia)
End If
Dim docComment = FormatDocumentComment(lineColumn, trivia)
changes.Add(docComment)
Return GetLineColumnDelta(lineColumn, docComment)
End Function
Private Function FormatStructuredTrivia(lineColumn As LineColumn,
trivia As SyntaxTrivia,
changes As ArrayBuilder(Of TextChange),
cancellationToken As CancellationToken) As LineColumnDelta
If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then
' don't touch anything if it contains skipped tokens
_succeeded = False
Return GetLineColumnDelta(lineColumn, trivia)
End If
' TODO : make document comment to be formatted by structured trivia formatter as well.
If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(
trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken)
If result.GetTextChanges(cancellationToken).Count = 0 Then
Return GetLineColumnDelta(lineColumn, trivia)
End If
changes.AddRange(result.GetTextChanges(cancellationToken))
Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax))
Return GetLineColumnDelta(lineColumn, formattedTrivia)
End If
Dim docComment = FormatDocumentComment(lineColumn, trivia)
If docComment <> trivia Then
changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString()))
End If
Return GetLineColumnDelta(lineColumn, docComment)
End Function
Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia
Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart)
Dim text = trivia.ToFullString()
' When the doc comment is parsed from source, even if it is only one
' line long, the end-of-line will get included into the trivia text.
' If the doc comment was parsed from a text fragment, there may not be
' an end-of-line at all. We need to trim the end before we check the
' number of line breaks in the text.
#If NETCOREAPP Then
Dim textWithoutFinalNewLine = text.TrimEnd()
#Else
Dim textWithoutFinalNewLine = text.TrimEnd(Nothing)
#End If
If Not textWithoutFinalNewLine.ContainsLineBreak() Then
Return trivia
End If
Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment(
forceIndentation:=True,
indentation:=indentation,
indentationDelta:=0,
useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs),
tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize),
newLine:=Me.Options.GetOption(FormattingOptions2.NewLine))
If text = singlelineDocComments Then
Return trivia
End If
Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments)
Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1)
Return singlelineDocCommentTrivia.ElementAt(0)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Portable/Syntax/WhileStatementSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class WhileStatementSyntax
{
public WhileStatementSyntax Update(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static WhileStatementSyntax WhileStatement(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement)
=> WhileStatement(attributeLists: default, whileKeyword, openParenToken, condition, closeParenToken, statement);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class WhileStatementSyntax
{
public WhileStatementSyntax Update(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static WhileStatementSyntax WhileStatement(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement)
=> WhileStatement(attributeLists: default, whileKeyword, openParenToken, condition, closeParenToken, statement);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.Generation.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.Editing
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Partial Public Class AutomationObject
Public Property Option_PlaceSystemNamespaceFirst As Boolean
Get
Return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst)
End Get
Set(value As Boolean)
SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value)
End Set
End Property
Public Property Option_SeparateImportDirectiveGroups As Boolean
Get
Return GetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups)
End Get
Set(value As Boolean)
SetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups, value)
End Set
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editing
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Partial Public Class AutomationObject
Public Property Option_PlaceSystemNamespaceFirst As Boolean
Get
Return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst)
End Get
Set(value As Boolean)
SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value)
End Set
End Property
Public Property Option_SeparateImportDirectiveGroups As Boolean
Get
Return GetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups)
End Get
Set(value As Boolean)
SetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups, value)
End Set
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/Syntax/TypeStatementSyntax.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class TypeStatementSyntax
Public ReadOnly Property Arity As Integer
Get
Return If(Me.TypeParameterList Is Nothing, 0, Me.TypeParameterList.Parameters.Count)
End Get
End Property
''' <summary>
''' Returns the keyword indicating the kind of declaration being made: "Class", "Structure", "Module", "Interface", etc.
''' </summary>
Public MustOverride ReadOnly Property DeclarationKeyword As SyntaxToken
''' <summary>
''' Returns a copy of this <see cref="TypeStatementSyntax"/> with the <see cref="DeclarationKeyword"/> property changed to the
''' specified value. Returns this instance if the specified value is the same as the current value.
''' </summary>
Public MustOverride Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. ClassKeyword) instead.", True)>
Public ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. WithClassKeyword) instead.", True)>
Public Function WithKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithDeclarationKeyword(keyword)
End Function
End Class
Partial Public Class ModuleStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return ModuleKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithModuleKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As ModuleStatementSyntax
Return WithModuleKeyword(keyword)
End Function
End Class
Partial Public Class StructureStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return StructureKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithStructureKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As StructureStatementSyntax
Return WithStructureKeyword(keyword)
End Function
End Class
Partial Public Class ClassStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return ClassKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithClassKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As ClassStatementSyntax
Return WithClassKeyword(keyword)
End Function
End Class
Partial Public Class InterfaceStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return InterfaceKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithInterfaceKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As InterfaceStatementSyntax
Return WithInterfaceKeyword(keyword)
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.ComponentModel
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class TypeStatementSyntax
Public ReadOnly Property Arity As Integer
Get
Return If(Me.TypeParameterList Is Nothing, 0, Me.TypeParameterList.Parameters.Count)
End Get
End Property
''' <summary>
''' Returns the keyword indicating the kind of declaration being made: "Class", "Structure", "Module", "Interface", etc.
''' </summary>
Public MustOverride ReadOnly Property DeclarationKeyword As SyntaxToken
''' <summary>
''' Returns a copy of this <see cref="TypeStatementSyntax"/> with the <see cref="DeclarationKeyword"/> property changed to the
''' specified value. Returns this instance if the specified value is the same as the current value.
''' </summary>
Public MustOverride Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. ClassKeyword) instead.", True)>
Public ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete. Use DeclarationKeyword or a more specific property (e.g. WithClassKeyword) instead.", True)>
Public Function WithKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithDeclarationKeyword(keyword)
End Function
End Class
Partial Public Class ModuleStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return ModuleKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithModuleKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As ModuleStatementSyntax
Return WithModuleKeyword(keyword)
End Function
End Class
Partial Public Class StructureStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return StructureKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithStructureKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As StructureStatementSyntax
Return WithStructureKeyword(keyword)
End Function
End Class
Partial Public Class ClassStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return ClassKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithClassKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As ClassStatementSyntax
Return WithClassKeyword(keyword)
End Function
End Class
Partial Public Class InterfaceStatementSyntax
Public Overrides ReadOnly Property DeclarationKeyword As SyntaxToken
Get
Return InterfaceKeyword
End Get
End Property
Public Overrides Function WithDeclarationKeyword(keyword As SyntaxToken) As TypeStatementSyntax
Return WithInterfaceKeyword(keyword)
End Function
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows ReadOnly Property Keyword As SyntaxToken
Get
Return DeclarationKeyword
End Get
End Property
<EditorBrowsable(EditorBrowsableState.Never)>
<Obsolete("This member is obsolete.", True)>
Public Shadows Function WithKeyword(keyword As SyntaxToken) As InterfaceStatementSyntax
Return WithInterfaceKeyword(keyword)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocument.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A <see cref="Document"/> that was generated by an <see cref="ISourceGenerator" />.
/// </summary>
public sealed class SourceGeneratedDocument : Document
{
internal SourceGeneratedDocument(Project project, SourceGeneratedDocumentState state)
: base(project, state)
{
}
private new SourceGeneratedDocumentState State => (SourceGeneratedDocumentState)base.State;
// TODO: make this public. Tracked by https://github.com/dotnet/roslyn/issues/50546
internal string SourceGeneratorAssemblyName => Identity.GeneratorAssemblyName;
internal string SourceGeneratorTypeName => Identity.GeneratorTypeName;
public string HintName => State.HintName;
internal SourceGeneratedDocumentIdentity Identity => State.Identity;
internal override Document WithFrozenPartialSemantics(CancellationToken cancellationToken)
{
// For us to implement frozen partial semantics here with a source generated document,
// we'd need to potentially deal with the combination where that happens on a snapshot that was already
// forked; rather than trying to deal with that combo we'll just fall back to not doing anything special
// which is allowed.
return this;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A <see cref="Document"/> that was generated by an <see cref="ISourceGenerator" />.
/// </summary>
public sealed class SourceGeneratedDocument : Document
{
internal SourceGeneratedDocument(Project project, SourceGeneratedDocumentState state)
: base(project, state)
{
}
private new SourceGeneratedDocumentState State => (SourceGeneratedDocumentState)base.State;
// TODO: make this public. Tracked by https://github.com/dotnet/roslyn/issues/50546
internal string SourceGeneratorAssemblyName => Identity.GeneratorAssemblyName;
internal string SourceGeneratorTypeName => Identity.GeneratorTypeName;
public string HintName => State.HintName;
internal SourceGeneratedDocumentIdentity Identity => State.Identity;
internal override Document WithFrozenPartialSemantics(CancellationToken cancellationToken)
{
// For us to implement frozen partial semantics here with a source generated document,
// we'd need to potentially deal with the combination where that happens on a snapshot that was already
// forked; rather than trying to deal with that combo we'll just fall back to not doing anything special
// which is allowed.
return this;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Scripting/CSharpTest/ScriptTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Test;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests
{
public class ScriptTests : TestBase
{
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateScript_CodeIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((string)null));
}
[Fact]
public void TestCreateFromStreamScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateFromStreamScript_StreamIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((Stream)null));
}
[Fact]
public async Task TestGetCompilation()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public async Task TestGetCompilationSourceText()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.SourceText, compilation.SyntaxTrees.First().GetText());
}
[Fact]
public void TestEmit_PortablePdb() => TestEmit(DebugInformationFormat.PortablePdb);
[ConditionalFact(typeof(WindowsOnly))]
public void TestEmit_WindowsPdb() => TestEmit(DebugInformationFormat.Pdb);
private void TestEmit(DebugInformationFormat format)
{
var script = CSharpScript.Create("1 + 2", options: ScriptOptions.Default.WithEmitDebugInformation(true));
var compilation = script.GetCompilation();
var emitOptions = ScriptBuilder.GetEmitOptions(emitDebugInformation: true).WithDebugInformationFormat(format);
var peStream = new MemoryStream();
var pdbStream = new MemoryStream();
var emitResult = ScriptBuilder.Emit(peStream, pdbStream, compilation, emitOptions, cancellationToken: default);
peStream.Position = 0;
pdbStream.Position = 0;
PdbValidation.ValidateDebugDirectory(
peStream,
portablePdbStreamOpt: (format == DebugInformationFormat.PortablePdb) ? pdbStream : null,
pdbPath: compilation.AssemblyName + ".pdb",
hashAlgorithm: default,
hasEmbeddedPdb: false,
isDeterministic: false);
}
[Fact]
public async Task TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
Assert.Equal(3, fn().Result);
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
}
[Fact]
public async Task TestCreateScriptDelegateWithGlobals()
{
// create a delegate for the entire script
var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals));
var fn = script.CreateDelegate();
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn());
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result);
}
[Fact]
public async Task TestRunScript()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateFromStreamAndRunScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestEvalScript()
{
var value = await CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value);
}
[Fact]
public async Task TestRunScriptWithSpecifiedReturnType()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public void TestRunVoidScript()
{
var state = ScriptingTestHelpers.RunScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine(0);"),
"0");
Assert.Null(state.ReturnValue);
}
[WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")]
[Fact]
public async Task TestRunExpressionStatement()
{
var state = await CSharpScript.RunAsync(
@"int F() { return 1; }
F();");
Assert.Null(state.ReturnValue);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public async Task TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
await CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public async Task TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
await CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementNotFollowedBySemicolon()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true)", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
ex.Diagnostics.Verify(
// (2,32): error CS1002: ; expected
// System.Console.WriteLine(true)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 32));
}
Assert.True(exceptionThrown);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementFollowedBySemicolon()
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true);", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedBySpace()
{
var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedByNewLineNoSemicolon()
{
var state = CSharpScript.RunAsync(@"
System.Console.WriteLine(true)
", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedNoSemicolonFollowedByAnotherStatement()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (e) a = b
throw e;", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single ExpectedSemicolon error.
// No duplicates for the same error.
ex.Diagnostics.Verify(
// (1,13): error CS1002: ; expected
// if (e) a = b
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 13));
}
Assert.True(exceptionThrown);
}
[Fact]
public async Task TestRunScriptWithGlobals()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
var state = await script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
Assert.Same(script, state.Script);
}
[Fact]
public async Task TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
// Global variables passed to a script without a global type
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 }));
}
[Fact]
public async Task TestRunCreatedScriptWithoutGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The script requires access to global variables but none were given
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync());
}
[Fact]
public async Task TestRunCreatedScriptWithMismatchedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals'
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object()));
}
[Fact]
public async Task ContinueAsync_Error1()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals());
await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null));
}
[Fact]
public async Task ContinueAsync_Error2()
{
var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals());
var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals());
await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2));
}
[Fact]
public async Task TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X");
Assert.Equal(200, state.ReturnValue);
}
[Fact]
public async Task TestRepl()
{
var submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
var state = await CSharpScript.RunAsync("");
foreach (var submission in submissions)
{
state = await state.ContinueWithAsync(submission);
}
Assert.Equal(10100, state.ReturnValue);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public async Task ScriptVariables_Chain()
{
var globals = new Globals { X = 10, Y = 20 };
var script =
CSharpScript.Create(
"var a = '1';",
globalsType: globals.GetType()).
ContinueWith("var b = 2u;").
ContinueWith("var a = 3m;").
ContinueWith("var x = a + b;").
ContinueWith("var X = Y;");
var state = await script.RunAsync(globals);
AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name));
AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value));
AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type));
Assert.Equal(3m, state.GetVariable("a").Value);
Assert.Equal(2u, state.GetVariable("b").Value);
Assert.Equal(5m, state.GetVariable("x").Value);
Assert.Equal(20, state.GetVariable("X").Value);
Assert.Null(state.GetVariable("A"));
Assert.Same(state.GetVariable("X"), state.GetVariable("X"));
}
[Fact]
public async Task ScriptVariable_SetValue()
{
var script = CSharpScript.Create("var x = 1;");
var s1 = await script.RunAsync();
s1.GetVariable("x").Value = 2;
Assert.Equal(2, s1.GetVariable("x").Value);
// rerunning the script from the beginning rebuilds the state:
var s2 = await s1.Script.RunAsync();
Assert.Equal(1, s2.GetVariable("x").Value);
// continuing preserves the state:
var s3 = await s1.ContinueWithAsync("x");
Assert.Equal(2, s3.GetVariable("x").Value);
Assert.Equal(2, s3.ReturnValue);
}
[Fact]
public async Task ScriptVariable_SetValue_Errors()
{
var state = await CSharpScript.RunAsync(@"
var x = 1;
readonly var y = 2;
const int z = 3;
");
Assert.False(state.GetVariable("x").IsReadOnly);
Assert.True(state.GetVariable("y").IsReadOnly);
Assert.True(state.GetVariable("z").IsReadOnly);
Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0);
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0);
}
[Fact]
public async Task TestBranchingSubscripts()
{
// run script to create declaration of M
var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)");
Assert.Equal(25, state2.ReturnValue);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var state3 = await state1.ContinueWithAsync("M(5)");
Assert.Equal(10, state3.ReturnValue);
}
[Fact]
public async Task ReturnIntAsObject()
{
var expected = 42;
var script = CSharpScript.Create<object>($"return {expected};");
var result = await script.EvaluateAsync();
Assert.Equal(expected, result);
}
[Fact]
public void NoReturn()
{
Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine();"), ""));
}
[Fact]
public async Task ReturnAwait()
{
var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);");
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInNestedScopeNoTrailingExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
Assert.Equal(1, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt()
{
var script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine()");
Assert.Equal(0, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnIntWithTrailingDoubleExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
1.1");
var result = await script.EvaluateAsync();
Assert.Equal(1.1, result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
1.1");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnGenericAsInterface()
{
var script = CSharpScript.Create<IEnumerable<int>>(@"
if (false)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create<IEnumerable<int>>(@"
if (true)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
result = await script.EvaluateAsync();
Assert.Equal(new List<int> { 1, 2, 3 }, result);
}
[Fact]
public async Task ReturnNullable()
{
var script = CSharpScript.Create<int?>(@"
if (false)
{
return 42;
}");
var result = await script.EvaluateAsync();
Assert.False(result.HasValue);
script = CSharpScript.Create<int?>(@"
if (true)
{
return 42;
}");
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFile()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 42;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
script = CSharpScript.Create(@"
#load ""a.csx""
-1", options);
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
if (false)
{
return 42;
}
1"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public void ReturnInLoadedFileTrailingVoidExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
if (false)
{
return 1;
}
System.Console.WriteLine(42)"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Equal(2, result);
}
[Fact]
public async Task MultipleLoadedFilesWithTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
3", options);
result = await script.EvaluateAsync();
Assert.Equal(3, result);
}
[Fact]
public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task LoadedFileWithReturnAndGoto()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
goto EOF;
NEXT:
return 1;
EOF:;
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"
#load ""a.csx""
goto NEXT;
return 3;
NEXT:;", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
L1: goto EOF;
L2: return 3;
EOF:
EOF2: ;
4", options);
result = await script.EvaluateAsync();
Assert.Equal(4, result);
}
[Fact]
public async Task VoidReturn()
{
var script = CSharpScript.Create("return;");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
var b = true;
if (b)
{
return;
}
b");
result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task LoadedFileWithVoidReturn()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
var i = 42;
return;
i = -1;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create<int>(@"
#load ""a.csx""
i", options);
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
[Fact]
public async Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithoutFileEncoding_CompilationErrorException()
{
var code = "throw new System.Exception();";
try
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(null);
var script = await CSharpScript.RunAsync(code, opts);
}
catch (CompilationErrorException ex)
{
// CS8055: Cannot emit debug information for a source text without encoding.
ex.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, code).WithLocation(1, 1));
}
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "debug.csx");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath(null).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx");
}
[Fact]
public Task Pdb_CreateFromStream_CodeFromFile_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromStream_InlineCode_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[WorkItem(12348, "https://github.com/dotnet/roslyn/issues/12348")]
[Fact]
public void StreamWithOffset()
{
var resolver = new StreamOffsetResolver();
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"#load ""a.csx""", options);
ScriptingTestHelpers.EvaluateScriptWithOutput(script, "Hello World!");
}
[Fact]
public void CreateScriptWithFeatureThatIsNotSupportedInTheSelectedLanguageVersion()
{
var script = CSharpScript.Create(@"string x = default;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default").
WithArguments("default literal", "7.1").
WithLocation(1, 12)
);
}
[Fact]
public void CreateScriptWithNullableContextWithCSharp8()
{
var script = CSharpScript.Create(@"#nullable enable
string x = null;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(2, 28)
);
}
[Fact, WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
public async Task SwitchPatternWithVar_WhenValidCode_ShouldReturnValidResult()
{
var code = @"
using System;
var data = ""data"";
var reply = data switch {
null => ""data are null"",
"""" => ""data are empty"",
_ => data
};
return reply;
";
var script = CSharpScript.Create(code, ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics();
var result = await script.EvaluateAsync();
Assert.Equal("data", result);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenNonExistentVariable_ShouldReturnNameNotInContextCompilationError()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = notExistentVariable switch { _ => null };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,12): error CS0103: The name 'notExistentVariable' does not exist in the current context
// var data = notExistentVariable switch { _ => null };
Diagnostic(ErrorCode.ERR_NameNotInContext, "notExistentVariable").WithArguments("notExistentVariable").WithLocation(1, 12));
}
Assert.True(exceptionThrown);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenInvalidPattern_ShouldReturnUnsupportedTypeForRelationalPatternAndNoImplicitConvErrors()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = ""data"" switch { < 5 => null };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,28): error CS8781: Relational patterns may not be used for a value of type 'string'.
// var data = "data" switch { < 5 => null };
Diagnostic(ErrorCode.ERR_UnsupportedTypeForRelationalPattern, "< 5").WithArguments("string").WithLocation(1, 28),
// (1,30): error CS0029: Cannot implicitly convert type 'int' to 'string'
// var data = "data" switch { < 5 => null };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "5").WithArguments("int", "string").WithLocation(1, 30));
}
Assert.True(exceptionThrown);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenInvalidArm_ShouldReturnTheNameNotInContextError()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = ""test"" switch { _ => armError };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,33): error CS0103: The name 'armError' does not exist in the current context
// var data = "test" switch { _ => armError };
Diagnostic(ErrorCode.ERR_NameNotInContext, "armError").WithArguments("armError")
.WithLocation(1, 33));
}
Assert.True(exceptionThrown);
}
private class StreamOffsetResolver : SourceReferenceResolver
{
public override bool Equals(object other) => ReferenceEquals(this, other);
public override int GetHashCode() => 42;
public override string ResolveReference(string path, string baseFilePath) => path;
public override string NormalizePath(string path, string baseFilePath) => path;
public override Stream OpenRead(string resolvedPath)
{
// Make an ASCII text buffer with Hello World script preceded by padding Qs
const int padding = 42;
string text = @"System.Console.WriteLine(""Hello World!"");";
byte[] bytes = Enumerable.Repeat((byte)'Q', text.Length + padding).ToArray();
System.Text.Encoding.ASCII.GetBytes(text, 0, text.Length, bytes, padding);
// Make a stream over the program portion, skipping the Qs.
var stream = new MemoryStream(
bytes,
padding,
text.Length,
writable: false,
publiclyVisible: true);
// sanity check that reading entire stream gives us back our text.
using (var streamReader = new StreamReader(
stream,
System.Text.Encoding.ASCII,
detectEncodingFromByteOrderMarks: false,
bufferSize: bytes.Length,
leaveOpen: true))
{
var textFromStream = streamReader.ReadToEnd();
Assert.Equal(textFromStream, text);
}
stream.Position = 0;
return stream;
}
}
private async Task VerifyStackTraceAsync(Func<Script<object>> scriptProvider, int line = 0, int column = 0, string filename = null)
{
try
{
var script = scriptProvider();
await script.RunAsync();
}
catch (Exception ex)
{
// line information is only available when PDBs have been emitted
var needFileInfo = true;
var stackTrace = new StackTrace(ex, needFileInfo);
var firstFrame = stackTrace.GetFrames()[0];
Assert.Equal(filename, firstFrame.GetFileName());
Assert.Equal(line, firstFrame.GetFileLineNumber());
Assert.Equal(column, firstFrame.GetFileColumnNumber());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Test;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests
{
public class ScriptTests : TestBase
{
public class Globals
{
public int X;
public int Y;
}
[Fact]
public void TestCreateScript()
{
var script = CSharpScript.Create("1 + 2");
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateScript_CodeIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((string)null));
}
[Fact]
public void TestCreateFromStreamScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
Assert.Equal("1 + 2", script.Code);
}
[Fact]
public void TestCreateFromStreamScript_StreamIsNull()
{
Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((Stream)null));
}
[Fact]
public async Task TestGetCompilation()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString());
}
[Fact]
public async Task TestGetCompilationSourceText()
{
var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests());
var compilation = state.Script.GetCompilation();
Assert.Equal(state.Script.SourceText, compilation.SyntaxTrees.First().GetText());
}
[Fact]
public void TestEmit_PortablePdb() => TestEmit(DebugInformationFormat.PortablePdb);
[ConditionalFact(typeof(WindowsOnly))]
public void TestEmit_WindowsPdb() => TestEmit(DebugInformationFormat.Pdb);
private void TestEmit(DebugInformationFormat format)
{
var script = CSharpScript.Create("1 + 2", options: ScriptOptions.Default.WithEmitDebugInformation(true));
var compilation = script.GetCompilation();
var emitOptions = ScriptBuilder.GetEmitOptions(emitDebugInformation: true).WithDebugInformationFormat(format);
var peStream = new MemoryStream();
var pdbStream = new MemoryStream();
var emitResult = ScriptBuilder.Emit(peStream, pdbStream, compilation, emitOptions, cancellationToken: default);
peStream.Position = 0;
pdbStream.Position = 0;
PdbValidation.ValidateDebugDirectory(
peStream,
portablePdbStreamOpt: (format == DebugInformationFormat.PortablePdb) ? pdbStream : null,
pdbPath: compilation.AssemblyName + ".pdb",
hashAlgorithm: default,
hasEmbeddedPdb: false,
isDeterministic: false);
}
[Fact]
public async Task TestCreateScriptDelegate()
{
// create a delegate for the entire script
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
Assert.Equal(3, fn().Result);
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
}
[Fact]
public async Task TestCreateScriptDelegateWithGlobals()
{
// create a delegate for the entire script
var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals));
var fn = script.CreateDelegate();
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn());
await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object()));
Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result);
}
[Fact]
public async Task TestRunScript()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateAndRunScript()
{
var script = CSharpScript.Create("1 + 2");
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestCreateFromStreamAndRunScript()
{
var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));
var state = await script.RunAsync();
Assert.Same(script, state.Script);
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestEvalScript()
{
var value = await CSharpScript.EvaluateAsync("1 + 2");
Assert.Equal(3, value);
}
[Fact]
public async Task TestRunScriptWithSpecifiedReturnType()
{
var state = await CSharpScript.RunAsync("1 + 2");
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public void TestRunVoidScript()
{
var state = ScriptingTestHelpers.RunScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine(0);"),
"0");
Assert.Null(state.ReturnValue);
}
[WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")]
[Fact]
public async Task TestRunExpressionStatement()
{
var state = await CSharpScript.RunAsync(
@"int F() { return 1; }
F();");
Assert.Null(state.ReturnValue);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public async Task TestRunDynamicVoidScriptWithTerminatingSemicolon()
{
await CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do();"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")]
public async Task TestRunDynamicVoidScriptWithoutTerminatingSemicolon()
{
await CSharpScript.RunAsync(@"
class SomeClass
{
public void Do()
{
}
}
dynamic d = new SomeClass();
d.Do()"
, ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef));
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementNotFollowedBySemicolon()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true)", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
ex.Diagnostics.Verify(
// (2,32): error CS1002: ; expected
// System.Console.WriteLine(true)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 32));
}
Assert.True(exceptionThrown);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedStatementFollowedBySemicolon()
{
var state = CSharpScript.RunAsync(@"if (true)
System.Console.WriteLine(true);", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedBySpace()
{
var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunStatementFollowedByNewLineNoSemicolon()
{
var state = CSharpScript.RunAsync(@"
System.Console.WriteLine(true)
", globals: new ScriptTests());
Assert.Null(state.Exception);
}
[WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")]
[Fact]
public void TestRunEmbeddedNoSemicolonFollowedByAnotherStatement()
{
var exceptionThrown = false;
try
{
var state = CSharpScript.RunAsync(@"if (e) a = b
throw e;", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single ExpectedSemicolon error.
// No duplicates for the same error.
ex.Diagnostics.Verify(
// (1,13): error CS1002: ; expected
// if (e) a = b
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 13));
}
Assert.True(exceptionThrown);
}
[Fact]
public async Task TestRunScriptWithGlobals()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
}
[Fact]
public async Task TestRunCreatedScriptWithExpectedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
var state = await script.RunAsync(new Globals { X = 1, Y = 2 });
Assert.Equal(3, state.ReturnValue);
Assert.Same(script, state.Script);
}
[Fact]
public async Task TestRunCreatedScriptWithUnexpectedGlobals()
{
var script = CSharpScript.Create("X + Y");
// Global variables passed to a script without a global type
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 }));
}
[Fact]
public async Task TestRunCreatedScriptWithoutGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The script requires access to global variables but none were given
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync());
}
[Fact]
public async Task TestRunCreatedScriptWithMismatchedGlobals()
{
var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals));
// The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals'
await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object()));
}
[Fact]
public async Task ContinueAsync_Error1()
{
var state = await CSharpScript.RunAsync("X + Y", globals: new Globals());
await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null));
}
[Fact]
public async Task ContinueAsync_Error2()
{
var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals());
var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals());
await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2));
}
[Fact]
public async Task TestRunScriptWithScriptState()
{
// run a script using another scripts end state as the starting state (globals)
var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X");
Assert.Equal(200, state.ReturnValue);
}
[Fact]
public async Task TestRepl()
{
var submissions = new[]
{
"int x = 100;",
"int y = x * x;",
"x + y"
};
var state = await CSharpScript.RunAsync("");
foreach (var submission in submissions)
{
state = await state.ContinueWithAsync(submission);
}
Assert.Equal(10100, state.ReturnValue);
}
#if TODO // https://github.com/dotnet/roslyn/issues/3720
[Fact]
public void TestCreateMethodDelegate()
{
// create a delegate to a method declared in the script
var state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate<Func<int, int>>("Times");
var result = fn(5);
Assert.Equal(25, result);
}
#endif
[Fact]
public async Task ScriptVariables_Chain()
{
var globals = new Globals { X = 10, Y = 20 };
var script =
CSharpScript.Create(
"var a = '1';",
globalsType: globals.GetType()).
ContinueWith("var b = 2u;").
ContinueWith("var a = 3m;").
ContinueWith("var x = a + b;").
ContinueWith("var X = Y;");
var state = await script.RunAsync(globals);
AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name));
AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value));
AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type));
Assert.Equal(3m, state.GetVariable("a").Value);
Assert.Equal(2u, state.GetVariable("b").Value);
Assert.Equal(5m, state.GetVariable("x").Value);
Assert.Equal(20, state.GetVariable("X").Value);
Assert.Null(state.GetVariable("A"));
Assert.Same(state.GetVariable("X"), state.GetVariable("X"));
}
[Fact]
public async Task ScriptVariable_SetValue()
{
var script = CSharpScript.Create("var x = 1;");
var s1 = await script.RunAsync();
s1.GetVariable("x").Value = 2;
Assert.Equal(2, s1.GetVariable("x").Value);
// rerunning the script from the beginning rebuilds the state:
var s2 = await s1.Script.RunAsync();
Assert.Equal(1, s2.GetVariable("x").Value);
// continuing preserves the state:
var s3 = await s1.ContinueWithAsync("x");
Assert.Equal(2, s3.GetVariable("x").Value);
Assert.Equal(2, s3.ReturnValue);
}
[Fact]
public async Task ScriptVariable_SetValue_Errors()
{
var state = await CSharpScript.RunAsync(@"
var x = 1;
readonly var y = 2;
const int z = 3;
");
Assert.False(state.GetVariable("x").IsReadOnly);
Assert.True(state.GetVariable("y").IsReadOnly);
Assert.True(state.GetVariable("z").IsReadOnly);
Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str");
Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0);
Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0);
}
[Fact]
public async Task TestBranchingSubscripts()
{
// run script to create declaration of M
var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }");
// run second script starting from first script's end state
// this script's new declaration should hide the old declaration
var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)");
Assert.Equal(25, state2.ReturnValue);
// run third script also starting from first script's end state
// it should not see any declarations made by the second script.
var state3 = await state1.ContinueWithAsync("M(5)");
Assert.Equal(10, state3.ReturnValue);
}
[Fact]
public async Task ReturnIntAsObject()
{
var expected = 42;
var script = CSharpScript.Create<object>($"return {expected};");
var result = await script.EvaluateAsync();
Assert.Equal(expected, result);
}
[Fact]
public void NoReturn()
{
Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput(
CSharpScript.Create("System.Console.WriteLine();"), ""));
}
[Fact]
public async Task ReturnAwait()
{
var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);");
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInNestedScopeNoTrailingExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
Assert.Equal(1, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt()
{
var script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine();");
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
script = CSharpScript.Create<int>(@"
bool condition = false;
if (condition)
{
return 1;
}
System.Console.WriteLine()");
Assert.Equal(0, ScriptingTestHelpers.EvaluateScriptWithOutput(script, ""));
}
[Fact]
public async Task ReturnIntWithTrailingDoubleExpression()
{
var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
return 1;
}
1.1");
var result = await script.EvaluateAsync();
Assert.Equal(1.1, result);
script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
return 1;
}
1.1");
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task ReturnGenericAsInterface()
{
var script = CSharpScript.Create<IEnumerable<int>>(@"
if (false)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create<IEnumerable<int>>(@"
if (true)
{
return new System.Collections.Generic.List<int> { 1, 2, 3 };
}");
result = await script.EvaluateAsync();
Assert.Equal(new List<int> { 1, 2, 3 }, result);
}
[Fact]
public async Task ReturnNullable()
{
var script = CSharpScript.Create<int?>(@"
if (false)
{
return 42;
}");
var result = await script.EvaluateAsync();
Assert.False(result.HasValue);
script = CSharpScript.Create<int?>(@"
if (true)
{
return 42;
}");
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFile()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 42;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(42, result);
script = CSharpScript.Create(@"
#load ""a.csx""
-1", options);
result = await script.EvaluateAsync();
Assert.Equal(42, result);
}
[Fact]
public async Task ReturnInLoadedFileTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
if (false)
{
return 42;
}
1"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = await script.EvaluateAsync();
Assert.Equal(2, result);
}
[Fact]
public void ReturnInLoadedFileTrailingVoidExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
if (false)
{
return 1;
}
System.Console.WriteLine(42)"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"a.csx\"", options);
var result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
2", options);
result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42");
Assert.Equal(2, result);
}
[Fact]
public async Task MultipleLoadedFilesWithTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Null(result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "1"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
3", options);
result = await script.EvaluateAsync();
Assert.Equal(3, result);
}
[Fact]
public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", @"
#load ""a.csx""
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create("#load \"b.csx\"", options);
var result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", "return 1;"),
KeyValuePairUtil.Create("b.csx", "2"));
options = ScriptOptions.Default.WithSourceResolver(resolver);
script = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
result = await script.EvaluateAsync();
Assert.Equal(1, result);
}
[Fact]
public async Task LoadedFileWithReturnAndGoto()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
goto EOF;
NEXT:
return 1;
EOF:;
2"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"
#load ""a.csx""
goto NEXT;
return 3;
NEXT:;", options);
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
#load ""a.csx""
L1: goto EOF;
L2: return 3;
EOF:
EOF2: ;
4", options);
result = await script.EvaluateAsync();
Assert.Equal(4, result);
}
[Fact]
public async Task VoidReturn()
{
var script = CSharpScript.Create("return;");
var result = await script.EvaluateAsync();
Assert.Null(result);
script = CSharpScript.Create(@"
var b = true;
if (b)
{
return;
}
b");
result = await script.EvaluateAsync();
Assert.Null(result);
}
[Fact]
public async Task LoadedFileWithVoidReturn()
{
var resolver = TestSourceReferenceResolver.Create(
KeyValuePairUtil.Create("a.csx", @"
var i = 42;
return;
i = -1;"));
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create<int>(@"
#load ""a.csx""
i", options);
var result = await script.EvaluateAsync();
Assert.Equal(0, result);
}
[Fact]
public async Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithoutFileEncoding_CompilationErrorException()
{
var code = "throw new System.Exception();";
try
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(null);
var script = await CSharpScript.RunAsync(code, opts);
}
catch (CompilationErrorException ex)
{
// CS8055: Cannot emit debug information for a source text without encoding.
ex.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, code).WithLocation(1, 1));
}
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "debug.csx");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath(null).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx");
}
[Fact]
public Task Pdb_CreateFromStream_CodeFromFile_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx");
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(null);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[Fact]
public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8);
return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")]
[WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")]
public Task Pdb_CreateFromStream_InlineCode_WithEmitDebugInformation_ResultInPdbEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(true);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "");
}
[Fact]
public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
{
var opts = ScriptOptions.Default.WithEmitDebugInformation(false);
return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts));
}
[WorkItem(12348, "https://github.com/dotnet/roslyn/issues/12348")]
[Fact]
public void StreamWithOffset()
{
var resolver = new StreamOffsetResolver();
var options = ScriptOptions.Default.WithSourceResolver(resolver);
var script = CSharpScript.Create(@"#load ""a.csx""", options);
ScriptingTestHelpers.EvaluateScriptWithOutput(script, "Hello World!");
}
[Fact]
public void CreateScriptWithFeatureThatIsNotSupportedInTheSelectedLanguageVersion()
{
var script = CSharpScript.Create(@"string x = default;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default").
WithArguments("default literal", "7.1").
WithLocation(1, 12)
);
}
[Fact]
public void CreateScriptWithNullableContextWithCSharp8()
{
var script = CSharpScript.Create(@"#nullable enable
string x = null;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(2, 28)
);
}
[Fact, WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
public async Task SwitchPatternWithVar_WhenValidCode_ShouldReturnValidResult()
{
var code = @"
using System;
var data = ""data"";
var reply = data switch {
null => ""data are null"",
"""" => ""data are empty"",
_ => data
};
return reply;
";
var script = CSharpScript.Create(code, ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8));
var compilation = script.GetCompilation();
compilation.VerifyDiagnostics();
var result = await script.EvaluateAsync();
Assert.Equal("data", result);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenNonExistentVariable_ShouldReturnNameNotInContextCompilationError()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = notExistentVariable switch { _ => null };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,12): error CS0103: The name 'notExistentVariable' does not exist in the current context
// var data = notExistentVariable switch { _ => null };
Diagnostic(ErrorCode.ERR_NameNotInContext, "notExistentVariable").WithArguments("notExistentVariable").WithLocation(1, 12));
}
Assert.True(exceptionThrown);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenInvalidPattern_ShouldReturnUnsupportedTypeForRelationalPatternAndNoImplicitConvErrors()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = ""data"" switch { < 5 => null };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,28): error CS8781: Relational patterns may not be used for a value of type 'string'.
// var data = "data" switch { < 5 => null };
Diagnostic(ErrorCode.ERR_UnsupportedTypeForRelationalPattern, "< 5").WithArguments("string").WithLocation(1, 28),
// (1,30): error CS0029: Cannot implicitly convert type 'int' to 'string'
// var data = "data" switch { < 5 => null };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "5").WithArguments("int", "string").WithLocation(1, 30));
}
Assert.True(exceptionThrown);
}
[WorkItem(49529, "https://github.com/dotnet/roslyn/issues/49529")]
[Fact]
public async Task SwitchPatternWithVar_WhenInvalidArm_ShouldReturnTheNameNotInContextError()
{
var exceptionThrown = false;
try
{
await CSharpScript.RunAsync(@"var data = ""test"" switch { _ => armError };", globals: new ScriptTests());
}
catch (CompilationErrorException ex)
{
exceptionThrown = true;
// Verify that it produces a single NameNotInContext error.
ex.Diagnostics.Verify(
// (1,33): error CS0103: The name 'armError' does not exist in the current context
// var data = "test" switch { _ => armError };
Diagnostic(ErrorCode.ERR_NameNotInContext, "armError").WithArguments("armError")
.WithLocation(1, 33));
}
Assert.True(exceptionThrown);
}
private class StreamOffsetResolver : SourceReferenceResolver
{
public override bool Equals(object other) => ReferenceEquals(this, other);
public override int GetHashCode() => 42;
public override string ResolveReference(string path, string baseFilePath) => path;
public override string NormalizePath(string path, string baseFilePath) => path;
public override Stream OpenRead(string resolvedPath)
{
// Make an ASCII text buffer with Hello World script preceded by padding Qs
const int padding = 42;
string text = @"System.Console.WriteLine(""Hello World!"");";
byte[] bytes = Enumerable.Repeat((byte)'Q', text.Length + padding).ToArray();
System.Text.Encoding.ASCII.GetBytes(text, 0, text.Length, bytes, padding);
// Make a stream over the program portion, skipping the Qs.
var stream = new MemoryStream(
bytes,
padding,
text.Length,
writable: false,
publiclyVisible: true);
// sanity check that reading entire stream gives us back our text.
using (var streamReader = new StreamReader(
stream,
System.Text.Encoding.ASCII,
detectEncodingFromByteOrderMarks: false,
bufferSize: bytes.Length,
leaveOpen: true))
{
var textFromStream = streamReader.ReadToEnd();
Assert.Equal(textFromStream, text);
}
stream.Position = 0;
return stream;
}
}
private async Task VerifyStackTraceAsync(Func<Script<object>> scriptProvider, int line = 0, int column = 0, string filename = null)
{
try
{
var script = scriptProvider();
await script.RunAsync();
}
catch (Exception ex)
{
// line information is only available when PDBs have been emitted
var needFileInfo = true;
var stackTrace = new StackTrace(ex, needFileInfo);
var firstFrame = stackTrace.GetFrames()[0];
Assert.Equal(filename, firstFrame.GetFileName());
Assert.Equal(line, firstFrame.GetFileLineNumber());
Assert.Equal(column, firstFrame.GetFileColumnNumber());
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/CSharp/Impl/CodeModel/ModifierFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.VisualStudio.LanguageServices.CSharp.CodeModel
{
[Flags]
internal enum ModifierFlags
{
// Note: These are in the order that they appear in modifier lists as generated by Code Model.
Public = 1 << 0,
Protected = 1 << 1,
Internal = 1 << 2,
Private = 1 << 3,
Virtual = 1 << 4,
Abstract = 1 << 5,
New = 1 << 6,
Override = 1 << 7,
Sealed = 1 << 8,
Static = 1 << 9,
Extern = 1 << 10,
Volatile = 1 << 11,
ReadOnly = 1 << 12,
Const = 1 << 13,
Unsafe = 1 << 14,
Async = 1 << 15,
Partial = 1 << 16,
AccessModifierMask = Private | Protected | Internal | Public
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.VisualStudio.LanguageServices.CSharp.CodeModel
{
[Flags]
internal enum ModifierFlags
{
// Note: These are in the order that they appear in modifier lists as generated by Code Model.
Public = 1 << 0,
Protected = 1 << 1,
Internal = 1 << 2,
Private = 1 << 3,
Virtual = 1 << 4,
Abstract = 1 << 5,
New = 1 << 6,
Override = 1 << 7,
Sealed = 1 << 8,
Static = 1 << 9,
Extern = 1 << 10,
Volatile = 1 << 11,
ReadOnly = 1 << 12,
Const = 1 << 13,
Unsafe = 1 << 14,
Async = 1 << 15,
Partial = 1 << 16,
AccessModifierMask = Private | Protected | Internal | Public
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/Binding/DeclarationInitializerBinder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used for field, auto property initializations and parameter default values.
''' </summary>
Friend NotInheritable Class DeclarationInitializerBinder
Inherits Binder
''' <summary>
''' Backing field for the ContainingMember property
''' </summary>
Private ReadOnly _symbol As Symbol
''' <summary>
''' Backing field for the AdditionalContainingMembers property
''' </summary>
Private ReadOnly _additionalSymbols As ImmutableArray(Of Symbol)
''' <summary> Root syntax node </summary>
Private ReadOnly _root As VisualBasicSyntaxNode
''' <summary>
''' Initializes a new instance of the <see cref="DeclarationInitializerBinder"/> class.
''' </summary>
''' <param name="symbol">The field, property or parameter symbol with an initializer or default value.</param>
''' <param name="additionalSymbols">Additional field for property symbols initialized with the initializer.</param>
''' <param name="next">The next binder.</param>
''' <param name="root">Root syntax node</param>
Public Sub New(symbol As Symbol, additionalSymbols As ImmutableArray(Of Symbol), [next] As Binder, root As VisualBasicSyntaxNode)
MyBase.New([next])
Debug.Assert((symbol.Kind = SymbolKind.Field) OrElse (symbol.Kind = SymbolKind.Property) OrElse (symbol.Kind = SymbolKind.Parameter))
Debug.Assert(additionalSymbols.All(Function(s) s.Kind = symbol.Kind AndAlso (s.Kind = SymbolKind.Field OrElse s.Kind = SymbolKind.Property)))
Debug.Assert(symbol.Kind <> SymbolKind.Parameter OrElse additionalSymbols.IsEmpty)
Me._symbol = symbol
Me._additionalSymbols = additionalSymbols
Debug.Assert(root IsNot Nothing)
_root = root
End Sub
''' <summary>
''' The member containing the binding context.
''' This property is the main reason for this binder, because the binding context for an initialization
''' needs to be the field or property symbol.
''' </summary>
Public Overrides ReadOnly Property ContainingMember As Symbol
Get
Return Me._symbol
End Get
End Property
''' <summary>
''' Additional members associated with the binding context
''' Currently, this field is only used for multiple field/property symbols initialized by an AsNew initializer, e.g. "Dim x, y As New Integer" or "WithEvents x, y as New Object"
''' </summary>
Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol)
Get
Return Me._additionalSymbols
End Get
End Property
''' <summary> Field or property declaration statement syntax node </summary>
Friend ReadOnly Property Root As VisualBasicSyntaxNode
Get
Return _root
End Get
End Property
' Initializers are expressions and so contain no descendant binders, except for lambda bodies, which are handled
' elsewhere (in MemberSemanticModel).
Public Overrides Function GetBinder(node As SyntaxNode) As Binder
Return Nothing
End Function
Public Overrides Function GetBinder(stmts As SyntaxList(Of StatementSyntax)) As Binder
Return Nothing
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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used for field, auto property initializations and parameter default values.
''' </summary>
Friend NotInheritable Class DeclarationInitializerBinder
Inherits Binder
''' <summary>
''' Backing field for the ContainingMember property
''' </summary>
Private ReadOnly _symbol As Symbol
''' <summary>
''' Backing field for the AdditionalContainingMembers property
''' </summary>
Private ReadOnly _additionalSymbols As ImmutableArray(Of Symbol)
''' <summary> Root syntax node </summary>
Private ReadOnly _root As VisualBasicSyntaxNode
''' <summary>
''' Initializes a new instance of the <see cref="DeclarationInitializerBinder"/> class.
''' </summary>
''' <param name="symbol">The field, property or parameter symbol with an initializer or default value.</param>
''' <param name="additionalSymbols">Additional field for property symbols initialized with the initializer.</param>
''' <param name="next">The next binder.</param>
''' <param name="root">Root syntax node</param>
Public Sub New(symbol As Symbol, additionalSymbols As ImmutableArray(Of Symbol), [next] As Binder, root As VisualBasicSyntaxNode)
MyBase.New([next])
Debug.Assert((symbol.Kind = SymbolKind.Field) OrElse (symbol.Kind = SymbolKind.Property) OrElse (symbol.Kind = SymbolKind.Parameter))
Debug.Assert(additionalSymbols.All(Function(s) s.Kind = symbol.Kind AndAlso (s.Kind = SymbolKind.Field OrElse s.Kind = SymbolKind.Property)))
Debug.Assert(symbol.Kind <> SymbolKind.Parameter OrElse additionalSymbols.IsEmpty)
Me._symbol = symbol
Me._additionalSymbols = additionalSymbols
Debug.Assert(root IsNot Nothing)
_root = root
End Sub
''' <summary>
''' The member containing the binding context.
''' This property is the main reason for this binder, because the binding context for an initialization
''' needs to be the field or property symbol.
''' </summary>
Public Overrides ReadOnly Property ContainingMember As Symbol
Get
Return Me._symbol
End Get
End Property
''' <summary>
''' Additional members associated with the binding context
''' Currently, this field is only used for multiple field/property symbols initialized by an AsNew initializer, e.g. "Dim x, y As New Integer" or "WithEvents x, y as New Object"
''' </summary>
Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol)
Get
Return Me._additionalSymbols
End Get
End Property
''' <summary> Field or property declaration statement syntax node </summary>
Friend ReadOnly Property Root As VisualBasicSyntaxNode
Get
Return _root
End Get
End Property
' Initializers are expressions and so contain no descendant binders, except for lambda bodies, which are handled
' elsewhere (in MemberSemanticModel).
Public Overrides Function GetBinder(node As SyntaxNode) As Binder
Return Nothing
End Function
Public Overrides Function GetBinder(stmts As SyntaxList(Of StatementSyntax)) As Binder
Return Nothing
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicExtensionMethodReducer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
Partial Friend Class VisualBasicExtensionMethodReducer
Inherits AbstractVisualBasicReducer
Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) =
New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool))
Public Sub New()
MyBase.New(s_pool)
End Sub
Private Shared ReadOnly s_simplifyInvocationExpression As Func(Of InvocationExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyInvocationExpression
Private Shared Function SimplifyInvocationExpression(
invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As InvocationExpressionSyntax
Dim rewrittenNode = invocationExpression
If invocationExpression.Expression?.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(invocationExpression.Expression, MemberAccessExpressionSyntax)
Dim targetSymbol = semanticModel.GetSymbolInfo(memberAccess.Name, cancellationToken)
If (Not targetSymbol.Symbol Is Nothing) AndAlso targetSymbol.Symbol.Kind = SymbolKind.Method Then
Dim targetMethodSymbol = DirectCast(targetSymbol.Symbol, IMethodSymbol)
If Not targetMethodSymbol.IsReducedExtension() Then
Dim argumentList = invocationExpression.ArgumentList
Dim noOfArguments = argumentList.Arguments.Count
If noOfArguments > 0 Then
Dim newMemberAccess = SyntaxFactory.SimpleMemberAccessExpression(argumentList.Arguments(0).GetArgumentExpression(), memberAccess.OperatorToken, memberAccess.Name)
' Below removes the first argument
' we need to reuse the separators to maintain existing formatting & comments in the arguments itself
Dim newArguments = SyntaxFactory.SeparatedList(Of ArgumentSyntax)(argumentList.Arguments.GetWithSeparators().AsEnumerable().Skip(2))
Dim rewrittenArgumentList = argumentList.WithArguments(newArguments)
Dim candidateRewrittenNode = SyntaxFactory.InvocationExpression(newMemberAccess, rewrittenArgumentList)
Dim oldSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol
Dim newSymbol = semanticModel.GetSpeculativeSymbolInfo(
invocationExpression.SpanStart,
candidateRewrittenNode,
SpeculativeBindingOption.BindAsExpression).Symbol
If Not oldSymbol Is Nothing And Not newSymbol Is Nothing Then
If newSymbol.Kind = SymbolKind.Method And oldSymbol.Equals(DirectCast(newSymbol, IMethodSymbol).GetConstructedReducedFrom()) Then
rewrittenNode = candidateRewrittenNode
End If
End If
End If
End If
End If
End If
Return rewrittenNode
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
Partial Friend Class VisualBasicExtensionMethodReducer
Inherits AbstractVisualBasicReducer
Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) =
New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool))
Public Sub New()
MyBase.New(s_pool)
End Sub
Private Shared ReadOnly s_simplifyInvocationExpression As Func(Of InvocationExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyInvocationExpression
Private Shared Function SimplifyInvocationExpression(
invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As InvocationExpressionSyntax
Dim rewrittenNode = invocationExpression
If invocationExpression.Expression?.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(invocationExpression.Expression, MemberAccessExpressionSyntax)
Dim targetSymbol = semanticModel.GetSymbolInfo(memberAccess.Name, cancellationToken)
If (Not targetSymbol.Symbol Is Nothing) AndAlso targetSymbol.Symbol.Kind = SymbolKind.Method Then
Dim targetMethodSymbol = DirectCast(targetSymbol.Symbol, IMethodSymbol)
If Not targetMethodSymbol.IsReducedExtension() Then
Dim argumentList = invocationExpression.ArgumentList
Dim noOfArguments = argumentList.Arguments.Count
If noOfArguments > 0 Then
Dim newMemberAccess = SyntaxFactory.SimpleMemberAccessExpression(argumentList.Arguments(0).GetArgumentExpression(), memberAccess.OperatorToken, memberAccess.Name)
' Below removes the first argument
' we need to reuse the separators to maintain existing formatting & comments in the arguments itself
Dim newArguments = SyntaxFactory.SeparatedList(Of ArgumentSyntax)(argumentList.Arguments.GetWithSeparators().AsEnumerable().Skip(2))
Dim rewrittenArgumentList = argumentList.WithArguments(newArguments)
Dim candidateRewrittenNode = SyntaxFactory.InvocationExpression(newMemberAccess, rewrittenArgumentList)
Dim oldSymbol = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol
Dim newSymbol = semanticModel.GetSpeculativeSymbolInfo(
invocationExpression.SpanStart,
candidateRewrittenNode,
SpeculativeBindingOption.BindAsExpression).Symbol
If Not oldSymbol Is Nothing And Not newSymbol Is Nothing Then
If newSymbol.Kind = SymbolKind.Method And oldSymbol.Equals(DirectCast(newSymbol, IMethodSymbol).GetConstructedReducedFrom()) Then
rewrittenNode = candidateRewrittenNode
End If
End If
End If
End If
End If
End If
Return rewrittenNode
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DeclarationTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class DeclarationTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub Declarations()
Const source =
"Class C
Private Shared F As Object
Shared Sub M(Of T)(x As Object)
Dim y As Object
If x Is Nothing Then
Dim z As Object
End If
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim resultProperties As ResultProperties = Nothing
Dim errorMessage As String = Nothing
Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"z = $3",
DkmEvaluationFlags.None,
ImmutableArray.Create(ObjectIdAlias(3, GetType(Integer))),
DebuggerDiagnosticFormatter.Instance,
resultProperties,
errorMessage,
missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData)
Assert.Empty(missingAssemblyIdentities)
Assert.Null(errorMessage)
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect Or DkmClrCompilationResultFlags.ReadOnlyResult)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 62 (0x3e)
.maxstack 4
.locals init (Object V_0, //y
Boolean V_1,
Object V_2,
System.Guid V_3)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""z""
IL_000f: ldloca.s V_3
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.3
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""z""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""$3""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: unbox.any ""Integer""
IL_0037: box ""Integer""
IL_003c: stind.ref
IL_003d: ret
}")
End Sub)
End Sub
<Fact>
Public Sub References()
Const source =
"Class C
Delegate Sub D()
Friend F As Object
Private Shared G As Object
Shared Sub M(Of T)(x As Object)
Dim y As Object
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim aliases = ImmutableArray.Create(
VariableAlias("x", GetType(String)),
VariableAlias("y", GetType(Integer)),
VariableAlias("t", GetType(Object)),
VariableAlias("d", "C"),
VariableAlias("f", GetType(Integer)))
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"If(If(If(If(If(x, y), T), F), DirectCast(D, C).F), C.G)",
DkmEvaluationFlags.TreatAsExpression,
aliases,
errorMessage,
testData)
Assert.Equal(testData.Methods.Count, 1)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (Object V_0) //y
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0006
IL_0004: pop
IL_0005: ldloc.0
IL_0006: dup
IL_0007: brtrue.s IL_0014
IL_0009: pop
IL_000a: ldstr ""t""
IL_000f: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0014: dup
IL_0015: brtrue.s IL_002c
IL_0017: pop
IL_0018: ldstr ""f""
IL_001d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0022: unbox.any ""Integer""
IL_0027: box ""Integer""
IL_002c: dup
IL_002d: brtrue.s IL_0044
IL_002f: pop
IL_0030: ldstr ""d""
IL_0035: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_003a: castclass ""C""
IL_003f: ldfld ""C.F As Object""
IL_0044: dup
IL_0045: brtrue.s IL_004d
IL_0047: pop
IL_0048: ldsfld ""C.G As Object""
IL_004d: ret
}
")
End Sub)
End Sub
<Fact>
Public Sub BindingError_Initializer()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"x = F()",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30451: 'F' is not declared. It may be inaccessible due to its protection level.")
End Sub)
End Sub
<WorkItem(1098750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098750")>
<Fact>
Public Sub ReferenceInSameDeclaration()
Const source =
"Module M
Function F(s As String) As String
Return s
End Function
Sub M(o As Object)
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"s = F(s)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 62 (0x3e)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""s""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""s""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""s""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String""
IL_0037: call ""Function M.F(String) As String""
IL_003c: stind.ref
IL_003d: ret
}")
testData = New CompilationTestData()
context.CompileExpression(
"M(If(t, t))",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 65 (0x41)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""t""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""t""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0028: dup
IL_0029: brtrue.s IL_0036
IL_002b: pop
IL_002c: ldstr ""t""
IL_0031: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0036: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_003b: call ""Sub M.M(Object)""
IL_0040: ret
}")
End Sub)
End Sub
<WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")>
<Fact>
Public Sub PassByRef()
Const source =
"Module M
Function F(Of T)(ByRef t1 As T) As T
t1 = Nothing
Return t1
End Function
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"F(o)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 47 (0x2f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""o""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""o""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: call ""Function M.F(Of Object)(ByRef Object) As Object""
IL_002d: pop
IL_002e: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Keyword()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"[Me] = [Class]",
DkmEvaluationFlags.None,
ImmutableArray.Create(VariableAlias("class")),
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 57 (0x39)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""Me""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""Me""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""class""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_0037: stind.ref
IL_0038: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Generic()
Const source =
"Class C
Shared Sub M(Of T)(x As T)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"y = x",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""y""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""y""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldarg.0
IL_0029: box ""T""
IL_002e: stind.ref
IL_002f: ret
}")
End Sub)
End Sub
<WorkItem(1101237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101237")>
<Fact>
Public Sub TypeChar()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData As CompilationTestData
' Object
testData = New CompilationTestData()
context.CompileExpression(
"x = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldc.i4.3
IL_0029: box ""Integer""
IL_002e: stind.ref
IL_002f: ret
}")
' Integer
testData = New CompilationTestData()
context.CompileExpression(
"x% = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Integer""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Integer)(String) As Integer""
IL_0028: ldc.i4.3
IL_0029: stind.i4
IL_002a: ret
}")
' Long
testData = New CompilationTestData()
context.CompileExpression(
"x& = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 44 (0x2c)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Long""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Long)(String) As Long""
IL_0028: ldc.i4.3
IL_0029: conv.i8
IL_002a: stind.i8
IL_002b: ret
}")
' Single
testData = New CompilationTestData()
context.CompileExpression(
"x! = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 47 (0x2f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Single""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Single)(String) As Single""
IL_0028: ldc.r4 3
IL_002d: stind.r4
IL_002e: ret
}")
' Double
testData = New CompilationTestData()
context.CompileExpression(
"x# = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Double""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Double)(String) As Double""
IL_0028: ldc.r8 3
IL_0031: stind.r8
IL_0032: ret
}")
' String
testData = New CompilationTestData()
context.CompileExpression(
"x$ = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""String""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of String)(String) As String""
IL_0028: ldc.i4.3
IL_0029: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String""
IL_002e: stind.ref
IL_002f: ret
}")
' Decimal
testData = New CompilationTestData()
context.CompileExpression(
"x@ = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Decimal""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Decimal)(String) As Decimal""
IL_0028: ldc.i4.3
IL_0029: conv.i8
IL_002a: newobj ""Sub Decimal..ctor(Long)""
IL_002f: stobj ""Decimal""
IL_0034: ret
}")
End Sub)
End Sub
''' <summary>
''' Should not allow names with '$' prefix.
''' </summary>
<WorkItem(1106819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106819")>
<Fact>
Public Sub NoPrefix()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
' $1
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"$1 = 1",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $exception
testData = New CompilationTestData()
result = context.CompileExpression(
"$1 = 2",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $ReturnValue
testData = New CompilationTestData()
result = context.CompileExpression(
"$ReturnValue = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $x
testData = New CompilationTestData()
result = context.CompileExpression(
"$x = 4",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
End Sub)
End Sub
<WorkItem(1101243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101243")>
<Fact>
Public Sub [ReDim]()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"ReDim a(3)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""a""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""a""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldc.i4.4
IL_0029: newarr ""Object""
IL_002e: stind.ref
IL_002f: ret
}")
testData = New CompilationTestData()
context.CompileExpression(
"ReDim Preserve a(3)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 68 (0x44)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""a""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""a""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""a""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: castclass ""System.Array""
IL_0037: ldc.i4.4
IL_0038: newarr ""Object""
IL_003d: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array""
IL_0042: stind.ref
IL_0043: ret
}")
End Sub)
End Sub
<WorkItem(1101318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101318")>
<Fact>
Public Sub CompoundAssignment()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"x += 1",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 63 (0x3f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""x""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: ldc.i4.1
IL_0033: box ""Integer""
IL_0038: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object""
IL_003d: stind.ref
IL_003e: ret
}")
End Sub)
End Sub
<WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")>
<Fact>
Public Sub CaseSensitivity()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"X",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(VariableAlias("x", GetType(String))),
errorMessage,
testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""x""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""String""
IL_000f: ret
}
")
End Sub)
End Sub
<WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")>
<Fact>
Public Sub CaseSensitivity_ImplicitDeclaration()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"x = X",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Null(errorMessage) ' Use before initialization is allowed in the EE.
' Note that all x's are lowercase (i.e. normalized).
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 57 (0x39)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""x""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_0037: stind.ref
IL_0038: ret
}
")
End Sub)
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 Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class DeclarationTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub Declarations()
Const source =
"Class C
Private Shared F As Object
Shared Sub M(Of T)(x As Object)
Dim y As Object
If x Is Nothing Then
Dim z As Object
End If
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim resultProperties As ResultProperties = Nothing
Dim errorMessage As String = Nothing
Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"z = $3",
DkmEvaluationFlags.None,
ImmutableArray.Create(ObjectIdAlias(3, GetType(Integer))),
DebuggerDiagnosticFormatter.Instance,
resultProperties,
errorMessage,
missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData)
Assert.Empty(missingAssemblyIdentities)
Assert.Null(errorMessage)
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect Or DkmClrCompilationResultFlags.ReadOnlyResult)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 62 (0x3e)
.maxstack 4
.locals init (Object V_0, //y
Boolean V_1,
Object V_2,
System.Guid V_3)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""z""
IL_000f: ldloca.s V_3
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.3
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""z""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""$3""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: unbox.any ""Integer""
IL_0037: box ""Integer""
IL_003c: stind.ref
IL_003d: ret
}")
End Sub)
End Sub
<Fact>
Public Sub References()
Const source =
"Class C
Delegate Sub D()
Friend F As Object
Private Shared G As Object
Shared Sub M(Of T)(x As Object)
Dim y As Object
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim aliases = ImmutableArray.Create(
VariableAlias("x", GetType(String)),
VariableAlias("y", GetType(Integer)),
VariableAlias("t", GetType(Object)),
VariableAlias("d", "C"),
VariableAlias("f", GetType(Integer)))
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"If(If(If(If(If(x, y), T), F), DirectCast(D, C).F), C.G)",
DkmEvaluationFlags.TreatAsExpression,
aliases,
errorMessage,
testData)
Assert.Equal(testData.Methods.Count, 1)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (Object V_0) //y
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0006
IL_0004: pop
IL_0005: ldloc.0
IL_0006: dup
IL_0007: brtrue.s IL_0014
IL_0009: pop
IL_000a: ldstr ""t""
IL_000f: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0014: dup
IL_0015: brtrue.s IL_002c
IL_0017: pop
IL_0018: ldstr ""f""
IL_001d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0022: unbox.any ""Integer""
IL_0027: box ""Integer""
IL_002c: dup
IL_002d: brtrue.s IL_0044
IL_002f: pop
IL_0030: ldstr ""d""
IL_0035: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_003a: castclass ""C""
IL_003f: ldfld ""C.F As Object""
IL_0044: dup
IL_0045: brtrue.s IL_004d
IL_0047: pop
IL_0048: ldsfld ""C.G As Object""
IL_004d: ret
}
")
End Sub)
End Sub
<Fact>
Public Sub BindingError_Initializer()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"x = F()",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30451: 'F' is not declared. It may be inaccessible due to its protection level.")
End Sub)
End Sub
<WorkItem(1098750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098750")>
<Fact>
Public Sub ReferenceInSameDeclaration()
Const source =
"Module M
Function F(s As String) As String
Return s
End Function
Sub M(o As Object)
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"s = F(s)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 62 (0x3e)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""s""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""s""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""s""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String""
IL_0037: call ""Function M.F(String) As String""
IL_003c: stind.ref
IL_003d: ret
}")
testData = New CompilationTestData()
context.CompileExpression(
"M(If(t, t))",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 65 (0x41)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""t""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""t""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0028: dup
IL_0029: brtrue.s IL_0036
IL_002b: pop
IL_002c: ldstr ""t""
IL_0031: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0036: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_003b: call ""Sub M.M(Object)""
IL_0040: ret
}")
End Sub)
End Sub
<WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")>
<Fact>
Public Sub PassByRef()
Const source =
"Module M
Function F(Of T)(ByRef t1 As T) As T
t1 = Nothing
Return t1
End Function
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"F(o)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 47 (0x2f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""o""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""o""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: call ""Function M.F(Of Object)(ByRef Object) As Object""
IL_002d: pop
IL_002e: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Keyword()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"[Me] = [Class]",
DkmEvaluationFlags.None,
ImmutableArray.Create(VariableAlias("class")),
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 57 (0x39)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""Me""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""Me""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""class""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_0037: stind.ref
IL_0038: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Generic()
Const source =
"Class C
Shared Sub M(Of T)(x As T)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"y = x",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""y""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""y""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldarg.0
IL_0029: box ""T""
IL_002e: stind.ref
IL_002f: ret
}")
End Sub)
End Sub
<WorkItem(1101237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101237")>
<Fact>
Public Sub TypeChar()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData As CompilationTestData
' Object
testData = New CompilationTestData()
context.CompileExpression(
"x = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldc.i4.3
IL_0029: box ""Integer""
IL_002e: stind.ref
IL_002f: ret
}")
' Integer
testData = New CompilationTestData()
context.CompileExpression(
"x% = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Integer""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Integer)(String) As Integer""
IL_0028: ldc.i4.3
IL_0029: stind.i4
IL_002a: ret
}")
' Long
testData = New CompilationTestData()
context.CompileExpression(
"x& = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 44 (0x2c)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Long""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Long)(String) As Long""
IL_0028: ldc.i4.3
IL_0029: conv.i8
IL_002a: stind.i8
IL_002b: ret
}")
' Single
testData = New CompilationTestData()
context.CompileExpression(
"x! = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 47 (0x2f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Single""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Single)(String) As Single""
IL_0028: ldc.r4 3
IL_002d: stind.r4
IL_002e: ret
}")
' Double
testData = New CompilationTestData()
context.CompileExpression(
"x# = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Double""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Double)(String) As Double""
IL_0028: ldc.r8 3
IL_0031: stind.r8
IL_0032: ret
}")
' String
testData = New CompilationTestData()
context.CompileExpression(
"x$ = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""String""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of String)(String) As String""
IL_0028: ldc.i4.3
IL_0029: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String""
IL_002e: stind.ref
IL_002f: ret
}")
' Decimal
testData = New CompilationTestData()
context.CompileExpression(
"x@ = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Decimal""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Decimal)(String) As Decimal""
IL_0028: ldc.i4.3
IL_0029: conv.i8
IL_002a: newobj ""Sub Decimal..ctor(Long)""
IL_002f: stobj ""Decimal""
IL_0034: ret
}")
End Sub)
End Sub
''' <summary>
''' Should not allow names with '$' prefix.
''' </summary>
<WorkItem(1106819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106819")>
<Fact>
Public Sub NoPrefix()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
' $1
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"$1 = 1",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $exception
testData = New CompilationTestData()
result = context.CompileExpression(
"$1 = 2",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $ReturnValue
testData = New CompilationTestData()
result = context.CompileExpression(
"$ReturnValue = 3",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
' $x
testData = New CompilationTestData()
result = context.CompileExpression(
"$x = 4",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Equal(errorMessage, "error BC30037: Character is not valid.")
End Sub)
End Sub
<WorkItem(1101243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101243")>
<Fact>
Public Sub [ReDim]()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"ReDim a(3)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 48 (0x30)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""a""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""a""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldc.i4.4
IL_0029: newarr ""Object""
IL_002e: stind.ref
IL_002f: ret
}")
testData = New CompilationTestData()
context.CompileExpression(
"ReDim Preserve a(3)",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 68 (0x44)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""a""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""a""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""a""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: castclass ""System.Array""
IL_0037: ldc.i4.4
IL_0038: newarr ""Object""
IL_003d: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array""
IL_0042: stind.ref
IL_0043: ret
}")
End Sub)
End Sub
<WorkItem(1101318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101318")>
<Fact>
Public Sub CompoundAssignment()
Const source =
"Module M
Sub M()
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(MakeSources(source, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName()), options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "M.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"x += 1",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 63 (0x3f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""x""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: ldc.i4.1
IL_0033: box ""Integer""
IL_0038: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object""
IL_003d: stind.ref
IL_003e: ret
}")
End Sub)
End Sub
<WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")>
<Fact>
Public Sub CaseSensitivity()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"X",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(VariableAlias("x", GetType(String))),
errorMessage,
testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""x""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""String""
IL_000f: ret
}
")
End Sub)
End Sub
<WorkItem(1115044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1115044")>
<Fact>
Public Sub CaseSensitivity_ImplicitDeclaration()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName())
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
Dim result = context.CompileExpression(
"x = X",
DkmEvaluationFlags.None,
NoAliases,
errorMessage,
testData)
Assert.Null(errorMessage) ' Use before initialization is allowed in the EE.
' Note that all x's are lowercase (i.e. normalized).
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 57 (0x39)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Object""
IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())""
IL_001e: ldstr ""x""
IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object""
IL_0028: ldstr ""x""
IL_002d: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0032: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_0037: stind.ref
IL_0038: ret
}
")
End Sub)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput>
{
private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func;
private readonly IEqualityComparer<TOutput> _comparer;
private readonly IIncrementalGeneratorNode<TInput> _sourceNode;
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null)
: this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer)
{
}
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null)
{
_sourceNode = sourceNode;
_func = userFunc;
_comparer = comparer ?? EqualityComparer<TOutput>.Default;
}
public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer);
public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken)
{
// grab the source inputs
var sourceTable = builder.GetLatestStateTableForNode(_sourceNode);
if (sourceTable.IsCached)
{
return previousTable;
}
// Semantics of a transform:
// Element-wise comparison of upstream table
// - Cached or Removed: no transform, just use previous values
// - Added: perform transform and add
// - Modified: perform transform and do element wise comparison with previous results
var newTable = previousTable.ToBuilder();
foreach (var entry in sourceTable)
{
if (entry.state == EntryState.Removed)
{
newTable.RemoveEntries();
}
else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries())
{
// generate the new entries
var newOutputs = _func(entry.item, cancellationToken);
if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer))
{
newTable.AddEntries(newOutputs, EntryState.Added);
}
}
}
return newTable.ToImmutableAndFree();
}
public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput>
{
private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func;
private readonly IEqualityComparer<TOutput> _comparer;
private readonly IIncrementalGeneratorNode<TInput> _sourceNode;
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null)
: this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer)
{
}
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null)
{
_sourceNode = sourceNode;
_func = userFunc;
_comparer = comparer ?? EqualityComparer<TOutput>.Default;
}
public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer);
public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken)
{
// grab the source inputs
var sourceTable = builder.GetLatestStateTableForNode(_sourceNode);
if (sourceTable.IsCached)
{
return previousTable;
}
// Semantics of a transform:
// Element-wise comparison of upstream table
// - Cached or Removed: no transform, just use previous values
// - Added: perform transform and add
// - Modified: perform transform and do element wise comparison with previous results
var newTable = previousTable.ToBuilder();
foreach (var entry in sourceTable)
{
if (entry.state == EntryState.Removed)
{
newTable.RemoveEntries();
}
else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries())
{
// generate the new entries
var newOutputs = _func(entry.item, cancellationToken);
if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer))
{
newTable.AddEntries(newOutputs, EntryState.Added);
}
}
}
return newTable.ToImmutableAndFree();
}
public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Core/Shared/Extensions/MefExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
/// <summary>
/// Helper class to perform ContentType best-match against a set of extensions. This could
/// become a public service.
/// </summary>
internal static class MefExtensions
{
/// <summary>
/// Given a list of extensions that provide content types, filter the list and return that
/// subset which matches the given content type
/// </summary>
public static IList<Lazy<TExtension, TMetadata>> SelectMatchingExtensions<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions((IEnumerable<IContentType>)contentTypes);
}
/// <summary>
/// Given a list of extensions that provide content types, filter the list and return that
/// subset which matches any of the given content types.
/// </summary>
public static IList<Lazy<TExtension, TMetadata>> SelectMatchingExtensions<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
IEnumerable<IContentType> contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.Where(h => contentTypes.Any(d => d.MatchesAny(h.Metadata.ContentTypes))).ToList();
}
public static IList<TExtension> SelectMatchingExtensionValues<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions(contentTypes).Select(p => p.Value).ToList();
}
public static Lazy<TExtension, TMetadata> SelectMatchingExtension<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions(contentTypes).Single();
}
public static TExtension SelectMatchingExtensionValue<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtension(contentTypes).Value;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
/// <summary>
/// Helper class to perform ContentType best-match against a set of extensions. This could
/// become a public service.
/// </summary>
internal static class MefExtensions
{
/// <summary>
/// Given a list of extensions that provide content types, filter the list and return that
/// subset which matches the given content type
/// </summary>
public static IList<Lazy<TExtension, TMetadata>> SelectMatchingExtensions<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions((IEnumerable<IContentType>)contentTypes);
}
/// <summary>
/// Given a list of extensions that provide content types, filter the list and return that
/// subset which matches any of the given content types.
/// </summary>
public static IList<Lazy<TExtension, TMetadata>> SelectMatchingExtensions<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
IEnumerable<IContentType> contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.Where(h => contentTypes.Any(d => d.MatchesAny(h.Metadata.ContentTypes))).ToList();
}
public static IList<TExtension> SelectMatchingExtensionValues<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions(contentTypes).Select(p => p.Value).ToList();
}
public static Lazy<TExtension, TMetadata> SelectMatchingExtension<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtensions(contentTypes).Single();
}
public static TExtension SelectMatchingExtensionValue<TExtension, TMetadata>(
this IEnumerable<Lazy<TExtension, TMetadata>> extensions,
params IContentType[] contentTypes)
where TMetadata : IContentTypeMetadata
{
return extensions.SelectMatchingExtension(contentTypes).Value;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/MethodTypeParameterSymbolReferenceFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class MethodTypeParameterSymbolReferenceFinder : AbstractReferenceFinder<ITypeParameterSymbol>
{
protected override bool CanFind(ITypeParameterSymbol symbol)
=> symbol.TypeParameterKind == TypeParameterKind.Method;
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
ITypeParameterSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var method = (IMethodSymbol)symbol.ContainingSymbol;
var ordinal = method.TypeParameters.IndexOf(symbol);
if (ordinal >= 0)
{
if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.TypeParameters.Length)
return Task.FromResult(ImmutableArray.Create<ISymbol>(method.PartialDefinitionPart.TypeParameters[ordinal]));
if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.TypeParameters.Length)
return Task.FromResult(ImmutableArray.Create<ISymbol>(method.PartialImplementationPart.TypeParameters[ordinal]));
}
return SpecializedTasks.EmptyImmutableArray<ISymbol>();
}
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
ITypeParameterSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// Type parameters are only found in documents that have both their name, and the name
// of its owning method. NOTE(cyrusn): We have to check in multiple files because of
// partial types. A type parameter can be referenced across all the parts. NOTE(cyrusn):
// We look for type parameters by name. This means if the same type parameter has a
// different name in different parts that we won't find it. However, this only happens
// in error situations. It is not legal in C# to use a different name for a type
// parameter in different parts.
//
// Also, we only look for files that have the name of the owning type. This helps filter
// down the set considerably.
Contract.ThrowIfNull(symbol.DeclaringMethod);
return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name,
GetMemberNameWithoutInterfaceName(symbol.DeclaringMethod.Name),
symbol.DeclaringMethod.ContainingType.Name);
}
private static string GetMemberNameWithoutInterfaceName(string fullName)
{
var index = fullName.LastIndexOf('.');
return index > 0
? fullName.Substring(index + 1)
: fullName;
}
protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
ITypeParameterSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// TODO(cyrusn): Method type parameters are like locals. They are only in scope in
// the bounds of the method they're declared within. We could improve perf by
// limiting our search by only looking within the method body's span.
return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class MethodTypeParameterSymbolReferenceFinder : AbstractReferenceFinder<ITypeParameterSymbol>
{
protected override bool CanFind(ITypeParameterSymbol symbol)
=> symbol.TypeParameterKind == TypeParameterKind.Method;
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
ITypeParameterSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var method = (IMethodSymbol)symbol.ContainingSymbol;
var ordinal = method.TypeParameters.IndexOf(symbol);
if (ordinal >= 0)
{
if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.TypeParameters.Length)
return Task.FromResult(ImmutableArray.Create<ISymbol>(method.PartialDefinitionPart.TypeParameters[ordinal]));
if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.TypeParameters.Length)
return Task.FromResult(ImmutableArray.Create<ISymbol>(method.PartialImplementationPart.TypeParameters[ordinal]));
}
return SpecializedTasks.EmptyImmutableArray<ISymbol>();
}
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
ITypeParameterSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// Type parameters are only found in documents that have both their name, and the name
// of its owning method. NOTE(cyrusn): We have to check in multiple files because of
// partial types. A type parameter can be referenced across all the parts. NOTE(cyrusn):
// We look for type parameters by name. This means if the same type parameter has a
// different name in different parts that we won't find it. However, this only happens
// in error situations. It is not legal in C# to use a different name for a type
// parameter in different parts.
//
// Also, we only look for files that have the name of the owning type. This helps filter
// down the set considerably.
Contract.ThrowIfNull(symbol.DeclaringMethod);
return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name,
GetMemberNameWithoutInterfaceName(symbol.DeclaringMethod.Name),
symbol.DeclaringMethod.ContainingType.Name);
}
private static string GetMemberNameWithoutInterfaceName(string fullName)
{
var index = fullName.LastIndexOf('.');
return index > 0
? fullName.Substring(index + 1)
: fullName;
}
protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
ITypeParameterSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// TODO(cyrusn): Method type parameters are like locals. They are only in scope in
// the bounds of the method they're declared within. We could improve perf by
// limiting our search by only looking within the method body's span.
return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.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.CodeStyle
Imports Microsoft.CodeAnalysis.CSharp.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class TypeNameSimplifierTest
Inherits AbstractSimplificationTests
#Region "Normal CSharp Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyTypeName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
class A
{
{|SimplifyParent:System.Exception|} c;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyReceiver1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:other.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
other.M(null);
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyReceiver2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:this.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
M(null);
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType2() As Task
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = N1.Preserve.X.Y;
}
}</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType3() As Task
' Simplified type is in a different namespace, whose names have been imported with a usings statement.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}
}</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType4() As Task
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = N1.N2.Outer.Preserve.X.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType5() As Task
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.NonGenericInner.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Outer.Preserve.X.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static {|SimplifyParent:C.B|} F()
{
return null;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static A.B F()
{
return null;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = {|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/19368")>
<Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Del|});
A.{|SimplifyParent:Del|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.Del);
Del();
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Bar|});
A.{|SimplifyParent:Bar|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.Bar);
A.Bar();
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Goo()
{
Boo(A.{|SimplifyParent:Boo|});
A.Boo(Boo);
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Goo()
{
Boo(A.Boo);
A.Boo(Boo);
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Action() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Goo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Goo()
{
A.Bar(3);
}
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Func() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Goo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Goo()
{
A.Bar(3);
}
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Inheritance() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.{|SimplifyParent:f|}();
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.f();
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyDoNothingWithFailedOverloadResolution() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Console;
class A
{
public void f()
{
Console.{|SimplifyParent:ReadLine|}("Boo!");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
using System.Console;
class A
{
public void f()
{
Console.ReadLine("Boo!");
}
}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(609496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609496")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpDoNotSimplifyNameInNamespaceDeclaration() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace System.{|SimplifyParent:Goo|}
{}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace System.Goo
{}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCS_EscapeAliasReplacementIfNeeded() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void goo()
{
var x = new System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() // Simplify Type Name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void goo()
{
var x = new @if() // Simplify Type Name
}
}
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(529989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529989")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCS_AliasReplacementKeepsUnicodeEscaping() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
System.Console.{|SimplifyParent:WriteLine|}("");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
B\u0061r.WriteLine("");
}
}
</Code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_Simplify_Cast_Type_Name() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((System.Collections.Generic.{|SimplifyParent:IEnumerable<int>|})a);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((IEnumerable<int>)a);
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestAliasedNameWithMethod() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using goo = System.Console;
class Program
{
static void Main(string[] args)
{
{|SimplifyExtension:System.Console.WriteLine|}("test");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
using goo = System.Console;
class Program
{
static void Main(string[] args)
{
goo.WriteLine("test");
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")>
Public Async Function TestSimplificationForDelegateCreation() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")>
Public Async Function TestSimplificationForDelegateCreation2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Goo()
{
(this.{|SimplifyParent:A|})(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Goo()
{
(this.A)(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Goo()
{
((this.{|SimplifyParent:A|}))(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Goo()
{
((A))(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Goo()
{
(this.{|SimplifyParent:d|}.A)(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Goo()
{
(this.d.A)(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(50, "https://github.com/dotnet/roslyn/issues/50")>
Public Async Function TestCSRemoveThisPreservesTrivia() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C1
{
int _field;
void M()
{
this /*comment 1*/ . /* comment 2 */ {|SimplifyParent:_field|} /* comment 3 */ = 0;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C1
{
int _field;
void M()
{
/*comment 1*/ /* comment 2 */ _field /* comment 3 */ = 0;
}
}
</code>
Await TestAsync(input, expected)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarLocalDeclaration() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void Main()
{
{|Simplify:int|} i = 0;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void Main()
{
var i = 0;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarForeachDecl() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections.Generic;
class Program
{
void Main()
{
foreach ({|Simplify:int|} item in new List<int>()) { }
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.Collections.Generic;
class Program
{
void Main()
{
foreach (var item in new List<int>()) { }
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarCorrect() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|Simplify:int|} i = 0;
for ({|Simplify:int|} j = 0; ;) { }
{|Simplify:D|} d = new D();
foreach ({|Simplify:int|} item in new List<int>()) { }
using ({|Simplify:StreamReader|} file = new StreamReader("C:\\myfile.txt")) {}
{|Simplify:int|} x = Goo();
}
static int Goo() { return 1; }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var i = 0;
for (var j = 0; ;) { }
var d = new D();
foreach (int item in new List<int>()) { }
using (var file = new StreamReader("C:\\myfile.txt")) {}
var x = Goo();
}
static int Goo() { return 1; }
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(734445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734445")>
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarCorrect_QualifiedTypeNames() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|SimplifyParent:N.C|} z = new N.C();
{|SimplifyParent:System.Int32|} i = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var z = new N.C();
var i = 1;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarDontSimplify() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
{|Simplify:int|} x;
static void Main(string[] args)
{
{|Simplify:int|} i = (i = 20);
{|Simplify:object|} o = null;
{|Simplify:Action<string[]>|} m = Main;
{|Simplify:int|} ij = 0, k = 0;
{|Simplify:int|} j;
{|Simplify:dynamic|} d = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Program
{
int x;
static void Main(string[] args)
{
int i = (i = 20);
object o = null;
Action<string[]> m = Main;
int ij = 0, k = 0;
int j;
dynamic d = 1;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWhenParentHasSimplifyAnnotation() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;|}
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
{|SpanToSimplify:System.Exception|} c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception {|SpanToSimplify:c;|}
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864735")>
Public Async Function TestBugFix864735_CSharp_SimplifyNameInIncompleteIsExpression() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static int F;
void M(C other)
{
Console.WriteLine({|SimplifyParent:C.F|} is
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
static int F;
void M(C other)
{
Console.WriteLine(F is
}
}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(813566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813566")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyQualifiedCref() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
/// <summary>
/// <see cref="{|Simplify:System.Object|}"/>
/// </summary>
class Program
{
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
using System;
/// <summary>
/// <see cref="object"/>
/// </summary>
class Program
{
}]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplifyToGenericNameCSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C.D.F();
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDoNotSimplifyToGenericName() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C.D.F();
}
}]]>
</text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplifyAllNodes_SimplifyNestedType() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}]]></text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameInCodeWithSyntaxErrors() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F({|SimplifyParent:this.x|});
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F(x);
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(653601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653601"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCrefSimplification_1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="Program"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(653601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653601"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCrefSimplification_2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program.B|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="B"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(966633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/966633"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyNullableQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
{|SimplifyParent:Nullable<long>|}.Value x;
void M({|SimplifyParent:Nullable<int>|} a, ref {|SimplifyParent:System.Nullable<int>|} b, ref {|SimplifyParent:Nullable<long>|}.Something c) { }
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
Nullable<long>.Value x;
void M(int? a, ref int? b, ref Nullable<long>.Something c) { }
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(965240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965240"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyOpenGenericNullable() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof({|SimplifyParent:System.Nullable<>|});
var y = (typeof({|SimplifyParent:System.Nullable<long>|}));
var z = (typeof({|SimplifyParent:System.Nullable|}));
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof(Nullable<>);
var y = (typeof(long?));
var z = (typeof(Nullable));
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(1067214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067214"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyTypeNameInExpressionBody_Property() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => (Program)x;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(1067214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067214"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyTypeNameInExpressionBody_Method() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => (Program)x;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyToPredefinedTypeNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new {|SimplifyParent:System.Int32|}.Blah;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new Int32.Blah;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyNullableInNameOfExpression() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof({|Simplify:Nullable<int>|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof(Nullable<int>);
}
}
]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsLHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
{|Simplify:this.i|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
this.i = 1;
}
}
]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsRHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
int x = {|Simplify:this.i|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
int x = this.i;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsMethodArgument_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M(int ii)
{
M({|Simplify:this.i|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M(int ii)
{
M(this.i);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
var s = {|Simplify:this.i|}.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
var s = this.i.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string s;
void M()
{
var x = {|Simplify:this.s|}?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string s;
void M()
{
var x = this.s?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsLHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
{|Simplify:this.i|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
this.i = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsRHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
int x = {|Simplify:this.i|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
int x = this.i;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsMethodArgument_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M(int ii)
{
M({|Simplify:this.i|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M(int ii)
{
M(this.i);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
var s = {|Simplify:this.i|}.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
var s = this.i.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string s { get; set; }
void M()
{
var x = {|Simplify:this.s|}?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string s { get; set; }
void M()
{
var x = this.s?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_AsVoidCallWithArguments_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
void M(int i)
{
{|Simplify:this.M|}(0);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
void M(int i)
{
this.M(0);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_WithReturnType_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int M()
{
return {|Simplify:this.M|}();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int M()
{
return this.M();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int M()
{
var s = {|Simplify:this.M|}().ToString();
return 0;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int M()
{
var s = this.M().ToString();
return 0;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string M()
{
return {|Simplify:this.M|}()?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string M()
{
return this.M()?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_EventSubscription_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
e += {|Simplify:this.Handler|};
e -= {|Simplify:this.Handler|};
e += new EventHandler({|Simplify:this.Handler|});
e -= new EventHandler({|Simplify:this.Handler|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
e += this.Handler;
e -= this.Handler;
e += new EventHandler(this.Handler);
e -= new EventHandler(this.Handler);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithThis_AddAndRemoveHandler_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
{|Simplify:this.e|} += Handler;
{|Simplify:this.e|} -= Handler;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
this.e += Handler;
this.e -= Handler;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithThis_InvokeEvent_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void OnSomeEvent()
{
{|Simplify:this.e|}(this, new EventArgs());
{|Simplify:this.e|}.Invoke(this, new EventArgs());
{|Simplify:this.e|}?.Invoke(this, new EventArgs());
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void OnSomeEvent()
{
this.e(this, new EventArgs());
this.e.Invoke(this, new EventArgs());
this.e?.Invoke(this, new EventArgs());
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.CSharp))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessNotPresentOnNotificationOptionSilent_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Silent))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionInfo_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Suggestion))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionWarning_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Warning))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionError_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Error))
End Function
#End Region
#Region "Normal Visual Basic Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyTypeName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
Class A
Private e As {|SimplifyParent:System.Exception|}
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Private e As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Array_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Goo() As Integer
Sub Main(args As String())
{|SimplifyParent:Program|}.Goo(23) = 23
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Goo() As Integer
Sub Main(args As String())
Goo(23) = 23
End Sub
End Module
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Array_2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
{|SimplifyParent:Program.Bar|}(2)(2)
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
Bar(2)(2)
End Sub
End Module
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:other.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
other.M(Nothing)
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:Me.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
M(Nothing)
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public Shared B As Action
Public Sub M(ab As A)
{|SimplifyParent:ab.B|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public Shared B As Action
Public Sub M(ab As A)
ab.B()
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim [Preserve].X.Y(1)
End Sub
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType2() As Task
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim N1.Preserve.X.Y(1)
End Sub
End Class</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType3() As Task
' Simplified type is in a different namespace, whose names have been imported with an Imports statement.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].X.Y(1)
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType4() As Task
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = N1.N2.Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType5() As Task
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).NonGenericInner.{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:Z(Of Single).Y(1)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As {|SimplifyParent:C.B|}
Return Nothing
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As A.B
Return Nothing
End Function
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:X.Y(1)|}
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate1_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Del|})
A.{|SimplifyParent:Del|}()
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.Del)
A.Del()
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate2_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Bar|})
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.Bar)
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(570986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570986")>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Action_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Goo()
A.{|SimplifyParent:Bar|}(3)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Goo()
A.Bar(3)
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyBaseInheritanceVB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
MustInherit Class A
Public MustOverride Sub Goo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Goo()
MyBase.{|SimplifyParent:Boo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
MustInherit Class A
Public MustOverride Sub Goo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Goo()
Boo()
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(588099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/588099")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_EscapeReservedNamesInAttributes() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
<Global.Assembly.{|SimplifyParent:Goo|}>
Module Assembly
Class GooAttribute
Inherits Attribute
End Class
End Module
Module M
Class GooAttribute
Inherits Attribute
End Class
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
<[Assembly].Goo>
Module Assembly
Class GooAttribute
Inherits Attribute
End Class
End Module
Module M
Class GooAttribute
Inherits Attribute
End Class
End Module
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_OmitModuleNameInMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
goo.Program.{|SimplifyParent:Main|}(Nothing)
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
goo.Main(Nothing)
End Sub
End Module
End Namespace
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_OmitModuleNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as goo.Program.{|SimplifyParent:C1|}
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as goo.C1
End Sub
End Module
End Namespace
</code>
Await TestAsync(input, expected)
End Function
<WorkItem(601160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601160")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestExpandMultilineLambdaWithImports() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
{|Expand:Sub Main(args As String())
Task.Run(Sub()
Imports System
End Sub)
End Sub|}
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(input)
Dim hostDocument = workspace.Documents.Single()
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim root = Await document.GetSyntaxRootAsync()
For Each span In hostDocument.AnnotatedSpans("Expand")
Dim node = root.FindToken(span.Start).Parent.Parent
If TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).Statements.Single()
End If
Assert.True(TypeOf node Is ExpressionStatementSyntax)
Dim result = Await Simplifier.ExpandAsync(node, document)
Assert.NotEqual(0, result.ToString().Count)
Next
End Using
End Function
<WorkItem(609496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609496")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_DoNotReduceNamesInNamespaceDeclarations() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace System.{|SimplifyParent:Goo|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports System
Namespace System.Goo
End Namespace
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_EscapeAliasReplacementIfNeeded() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() ' Simplify Type Name
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New [In]() ' Simplify Type Name
End Module
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_NoNREForOmittedReceiverInWithBlock() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Sub M()
With New B()
Dim x = .P.{|SimplifyParent:MaxValue|}
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Public Class A
Public Sub M()
With New B()
Dim x = .P.MaxValue
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(639971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639971")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestBugFix639971_VisualBasic_FalseUnnecessaryBaseQualifier() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Public Function Bar() As String
Return MyBase.{|SimplifyParent:ToString|}()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Class Z
Public Function Bar() As String
Return MyBase.ToString()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(639971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639971")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestBugFix639971_CSharp_FalseUnnecessaryBaseQualifier() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public string InvokeBaseToString()
{
return base.{|SimplifyParent:ToString|}();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using System;
class C
{
public string InvokeBaseToString()
{
return base.ToString();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWhenParentHasSimplifyAnnotation() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System|}
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As {|SpanToSimplify:System.Exception|}
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
{|SpanToSimplify:Dim c|} As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(769354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769354")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameInCrefCausesConflict() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="{|SimplifyParent:Global.Base|}.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="Base.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864735")>
Public Async Function TestBugFix864735_VisualBasic_SimplifyNameInIncompleteIsExpression() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf {|SimplifyParent:C.F|} Is
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf F Is
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(813566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813566")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyQualifiedCref() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
''' <summary>
''' <see cref="{|Simplify:System.Object|}"/>
''' </summary>
Class Program
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
''' <summary>
''' <see cref="Object"/>
''' </summary>
Class Program
End Class]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyToGenericName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C.D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DoNotSimplifyToGenericName() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C.D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestDontSimplifyAllNodes_SimplifyNestedType() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim [Preserve].X.Y(1)
End Sub
End Class]]></text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(881746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881746"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_SimplyToAlias() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:Attribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(881746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881746"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyAlias() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:AttributeAttributeAttribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(966633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/966633"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyNullableQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as {|SimplifyParent:Nullable(Of Integer)|}.Value
End Sub
Sub M(a as {|SimplifyParent:Nullable(Of Integer)|}, byref b as {|SimplifyParent:System.Nullable(Of Integer)|}, byref c as {|SimplifyParent:Nullable(Of Integer)|}.Value)
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as Nullable(Of Integer).Value
End Sub
Sub M(a as Integer?, byref b as Integer?, byref c as Nullable(Of Integer).Value)
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(965240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965240"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyOpenGenericNullable() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType({|SimplifyParent:System.Nullable(Of )|})
Dim y = (GetType({|SimplifyParent:System.Nullable(Of Long)|}))
Dim z = (GetType({|SimplifyParent:System.Nullable|}))
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType(Nullable(Of ))
Dim y = (GetType(Long?))
Dim z = (GetType(Nullable))
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<WpfFact(Skip:="1019361"), WorkItem(1019361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019361"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_Bug1019361() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = {|SimplifyParent:N.A|}.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = N.A.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyToPredefinedTypeNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New {|SimplifyParent:System.Int32|}.Blah
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New System.Int32.Blah
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyNullableInNameOfExpression() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf({|Simplify:Nullable(Of Integer)|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf(Nullable(Of Integer))
End Sum
End Class
]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsLHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
{|Simplify:Me.i|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Me.i = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsRHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim x = {|Simplify:Me.i|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim x = Me.i
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsMethodArgument_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M(ii As Integer)
M({|Simplify:Me.i|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M(ii As Integer)
M(Me.i)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim s = {|Simplify:Me.i|}.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim s = Me.i.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim s As String
Sub M()
Dim x = {|Simplify:Me.s|}?.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim s As String
Sub M()
Dim x = Me.s?.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsLHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
{|Simplify:Me.i|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Me.i = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsRHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim x = {|Simplify:Me.i|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim x = Me.i
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsMethodArgument_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M(ii As Integer)
M({|Simplify:Me.i|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M(ii As Integer)
M(Me.i)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim s = {|Simplify:Me.i|}.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim s = Me.i.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property s As String
Sub M()
Dim x = {|Simplify:Me.s|}?.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property s As String
Sub M()
Dim x = Me.s?.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_AsSubCallWithArguments_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Sub M(i As Integer)
{|Simplify:Me.M|}(0)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Sub M(i As Integer)
Me.M(0)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_WithReturnType_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As Integer
Return {|Simplify:Me.M|}()
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As Integer
Return Me.M()
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As Integer
Dim s = {|Simplify:Me.M|}().ToString()
Return 0
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As Integer
Dim s = Me.M().ToString()
Return 0
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As String
Return {|Simplify:Me.M|}()?.ToString()
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As String
Return Me.M()?.ToString()
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_EventSubscription_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler e, AddressOf {|Simplify:Me.Handler|}
RemoveHandler e, AddressOf {|Simplify:Me.Handler|}
AddHandler e, New EventHandler(AddressOf {|Simplify:Me.Handler|})
RemoveHandler e, New EventHandler(AddressOf {|Simplify:Me.Handler|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler e, AddressOf Me.Handler
RemoveHandler e, AddressOf Me.Handler
AddHandler e, New EventHandler(AddressOf Me.Handler)
RemoveHandler e, New EventHandler(AddressOf Me.Handler)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithMe_AddAndRemoveHandler_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler {|Simplify:Me.e|}, AddressOf Handler
RemoveHandler {|Simplify:Me.e|}, AddressOf Handler
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler Me.e, AddressOf Handler
RemoveHandler Me.e, AddressOf Handler
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.VisualBasic))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessNotPresentOnNotificationOptionSilent_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Silent))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionInfo_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Suggestion))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionWarning_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Warning))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionError_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Error))
End Function
<WorkItem(7955, "https://github.com/dotnet/roslyn/issues/7955")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function UsePredefinedTypeKeywordIfTextIsTheSame() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M(p As {|Simplify:[String]|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M(p As String)
End Sum
End Class
]]></text>
Await TestAsync(input, expected, DontPreferIntrinsicPredefinedTypeKeywordInDeclaration)
End Function
<WorkItem(7955, "https://github.com/dotnet/roslyn/issues/7955")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function DontUsePredefinedTypeKeyword() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M(p As {|Simplify:Int32|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M(p As Int32)
End Sum
End Class
]]></text>
Await TestAsync(input, expected, DontPreferIntrinsicPredefinedTypeKeywordInDeclaration)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSharedMemberOffOfMe() As Task
' even if the user prefers qualified member access, we will strip off 'Me' when calling
' a static method through it.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class Class1
Sub Main()
{|SimplifyParent:Me.Goo|}()
End Sub
Shared Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class Class1
Sub Main()
Goo()
End Sub
Shared Sub Goo()
End Sub
End Class
]]></text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
#End Region
#Region "Helpers"
Private Protected Shared Function QualifyFieldAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyPropertyAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return QualifyPropertyAccessOptionWithNotification(languageName, NotificationOption2.Error)
End Function
Private Protected Shared Function QualifyMethodAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyMethodAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyEventAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyEventAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyPropertyAccessOptionWithNotification(languageName As String, notification As NotificationOption2) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyPropertyAccess, languageName), New CodeStyleOption2(Of Boolean)(True, notification)}}
End Function
Private Shared ReadOnly DontPreferIntrinsicPredefinedTypeKeywordInDeclaration As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic), CodeStyleOption2(Of Boolean).Default}}
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.CSharp.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class TypeNameSimplifierTest
Inherits AbstractSimplificationTests
#Region "Normal CSharp Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyTypeName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
class A
{
{|SimplifyParent:System.Exception|} c;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyReceiver1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:other.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
other.M(null);
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyReceiver2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M(C other)
{
{|SimplifyParent:this.M|}(null);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
void M(C other)
{
M(null);
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType2() As Task
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
static class M
{
public static void Main()
{
int k = N1.Preserve.X.Y;
}
}</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType3() As Task
' Simplified type is in a different namespace, whose names have been imported with a usings statement.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = P.NonGeneric.{|SimplifyParent:X|}.Y;
}
}
} </Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace N1
{
class Preserve
{
public class X
{
public static int Y;
}
}
}
namespace P
{
class NonGeneric : N1.Preserve
{
}
}
namespace R
{
using N1;
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}
}</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType4() As Task
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
namespace P2
{
public class NonGeneric : N1.N2.Outer.Preserve
{
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using Q1.Q2;
static class M
{
public static void Main()
{
int k = N1.N2.Outer.Preserve.X.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyNestedType5() As Task
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Generic<int>.NonGenericInner.{|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N1
{
namespace N2
{
public class Outer
{
public class Preserve
{
public class X
{
public static int Y;
}
}
}
}
}
namespace P1
{
using N1.N2;
namespace P2
{
public class NonGeneric : Outer
{
public class NonGenericInner : Outer.Preserve
{
}
}
}
}
namespace Q1
{
using P1.P2;
namespace Q2
{
class Generic<T> : NonGeneric
{
}
}
}
namespace R
{
using N1.N2;
using Q1.Q2;
static class M
{
public static void Main()
{
int k = Outer.Preserve.X.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static {|SimplifyParent:C.B|} F()
{
return null;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
public static class B { }
}
class C : A
{
}
namespace N1
{
static class M
{
public static A.B F()
{
return null;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = {|SimplifyParent:X|}.Y;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public static int Y;
}
class NonGeneric : Preserve
{
}
namespace N1
{
using X = NonGeneric;
static class M
{
public static void Main()
{
int k = Preserve.Y;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/19368")>
<Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Del|});
A.{|SimplifyParent:Del|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Del() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del(A.Del);
Del();
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.{|SimplifyParent:Bar|});
A.{|SimplifyParent:Bar|}();
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
static void Bar() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del(A.Bar);
A.Bar();
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Goo()
{
Boo(A.{|SimplifyParent:Boo|});
A.Boo(Boo);
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
delegate void Del(Del a);
static void Boo(Del a) { }
class B
{
Del Boo = new Del(A.Boo);
void Goo()
{
Boo(A.Boo);
A.Boo(Boo);
}
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Action() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Goo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Action<int> Bar = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Goo()
{
A.Bar(3);
}
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Func() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Goo()
{
A.{|SimplifyParent:Bar|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class A
{
static Func<int,int> Bar = (int x) => { return x; };
class B
{
Func<int,int> Bar = (int x) => { return x; };
void Goo()
{
A.Bar(3);
}
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Inheritance() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.{|SimplifyParent:f|}();
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
class A
{
public virtual void f() { }
}
class B : A
{
public override void f()
{
base.f();
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyDoNothingWithFailedOverloadResolution() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Console;
class A
{
public void f()
{
Console.{|SimplifyParent:ReadLine|}("Boo!");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
using System.Console;
class A
{
public void f()
{
Console.ReadLine("Boo!");
}
}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(609496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609496")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpDoNotSimplifyNameInNamespaceDeclaration() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace System.{|SimplifyParent:Goo|}
{}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace System.Goo
{}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCS_EscapeAliasReplacementIfNeeded() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void goo()
{
var x = new System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() // Simplify Type Name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using @if = System.Runtime.InteropServices.InAttribute;
class C
{
void goo()
{
var x = new @if() // Simplify Type Name
}
}
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(529989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529989")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCS_AliasReplacementKeepsUnicodeEscaping() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
System.Console.{|SimplifyParent:WriteLine|}("");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using B\u0061r = System.Console;
class Program
{
static void Main(string[] args)
{
B\u0061r.WriteLine("");
}
}
</Code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_Simplify_Cast_Type_Name() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((System.Collections.Generic.{|SimplifyParent:IEnumerable<int>|})a);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
class C
{
void M()
{
var a = 1;
Console.WriteLine((IEnumerable<int>)a);
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestAliasedNameWithMethod() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using goo = System.Console;
class Program
{
static void Main(string[] args)
{
{|SimplifyExtension:System.Console.WriteLine|}("test");
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
using System.Collections.Generic;
using goo = System.Console;
class Program
{
static void Main(string[] args)
{
goo.WriteLine("test");
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")>
Public Async Function TestSimplificationForDelegateCreation() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
static void Main(string[] args)
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")>
Public Async Function TestSimplificationForDelegateCreation2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
Action b = (Action)Console.WriteLine + {|SimplifyParent:System.Console.WriteLine|};
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Test
{
Action b = (Action)Console.WriteLine + Console.WriteLine;
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Goo()
{
(this.{|SimplifyParent:A|})(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Goo()
{
(this.A)(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
Action A { get; set; }
void Goo()
{
((this.{|SimplifyParent:A|}))(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class C
{
Action A { get; set; }
void Goo()
{
((A))(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(576970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576970")>
Public Async Function TestCSRemoveThisWouldBeConsideredACast_3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Goo()
{
(this.{|SimplifyParent:d|}.A)(); // Simplify type name
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
public class C
{
public class D
{
public Action A { get; set; }
}
public D d = new D();
void Goo()
{
(this.d.A)(); // Simplify type name
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(50, "https://github.com/dotnet/roslyn/issues/50")>
Public Async Function TestCSRemoveThisPreservesTrivia() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C1
{
int _field;
void M()
{
this /*comment 1*/ . /* comment 2 */ {|SimplifyParent:_field|} /* comment 3 */ = 0;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class C1
{
int _field;
void M()
{
/*comment 1*/ /* comment 2 */ _field /* comment 3 */ = 0;
}
}
</code>
Await TestAsync(input, expected)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarLocalDeclaration() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void Main()
{
{|Simplify:int|} i = 0;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void Main()
{
var i = 0;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarForeachDecl() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections.Generic;
class Program
{
void Main()
{
foreach ({|Simplify:int|} item in new List<int>()) { }
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.Collections.Generic;
class Program
{
void Main()
{
foreach (var item in new List<int>()) { }
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarCorrect() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|Simplify:int|} i = 0;
for ({|Simplify:int|} j = 0; ;) { }
{|Simplify:D|} d = new D();
foreach ({|Simplify:int|} item in new List<int>()) { }
using ({|Simplify:StreamReader|} file = new StreamReader("C:\\myfile.txt")) {}
{|Simplify:int|} x = Goo();
}
static int Goo() { return 1; }
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
using I = N.C;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var i = 0;
for (var j = 0; ;) { }
var d = new D();
foreach (int item in new List<int>()) { }
using (var file = new StreamReader("C:\\myfile.txt")) {}
var x = Goo();
}
static int Goo() { return 1; }
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(734445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734445")>
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarCorrect_QualifiedTypeNames() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {
{CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement},
{CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement}
}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
{|SimplifyParent:N.C|} z = new N.C();
{|SimplifyParent:System.Int32|} i = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System.IO;
namespace N { class C {} }
class Program
{
class D { }
static void Main(string[] args)
{
var z = new N.C();
var i = 1;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<WorkItem(649385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649385")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharpSimplifyToVarDontSimplify() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
{|Simplify:int|} x;
static void Main(string[] args)
{
{|Simplify:int|} i = (i = 20);
{|Simplify:object|} o = null;
{|Simplify:Action<string[]>|} m = Main;
{|Simplify:int|} ij = 0, k = 0;
{|Simplify:int|} j;
{|Simplify:dynamic|} d = 1;
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
using System;
class Program
{
int x;
static void Main(string[] args)
{
int i = (i = 20);
object o = null;
Action<string[]> m = Main;
int ij = 0, k = 0;
int j;
dynamic d = 1;
}
}
</code>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWhenParentHasSimplifyAnnotation() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;|}
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
{|SpanToSimplify:using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception c;
}|}
}
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
{|SpanToSimplify:System.Exception|} c;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace Root
{
{|SimplifyParent:class A
{
System.Exception {|SpanToSimplify:c;|}
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
using System;
namespace Root
{
class A
{
System.Exception c;
}
}
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864735")>
Public Async Function TestBugFix864735_CSharp_SimplifyNameInIncompleteIsExpression() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static int F;
void M(C other)
{
Console.WriteLine({|SimplifyParent:C.F|} is
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
class C
{
static int F;
void M(C other)
{
Console.WriteLine(F is
}
}
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(813566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813566")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyQualifiedCref() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
/// <summary>
/// <see cref="{|Simplify:System.Object|}"/>
/// </summary>
class Program
{
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
using System;
/// <summary>
/// <see cref="object"/>
/// </summary>
class Program
{
}]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplifyToGenericNameCSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C.D.F();
}
}]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDoNotSimplifyToGenericName() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
{|SimplifyParent:C.D|}.F();
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
public class C<T>
{
public class D
{
public static void F()
{
}
}
}
public class C : C<int>
{
}
class E
{
public static void Main()
{
C.D.F();
}
}]]>
</text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplifyAllNodes_SimplifyNestedType() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = {|SimplifyParent:Z<float>.X.Y|};
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class Preserve
{
public class X
{
public static int Y;
}
}
class Z<T> : Preserve
{
}
static class M
{
public static void Main()
{
int k = Preserve.X.Y;
}
}]]></text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyTypeNameInCodeWithSyntaxErrors() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F({|SimplifyParent:this.x|});
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
private int x;
void F(int y) {}
void M()
{
C
// some comment
F(x);
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(653601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653601"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCrefSimplification_1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="Program"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(653601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653601"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCrefSimplification_2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="{|Simplify:A.Program.B|}"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace A
{
/// <summary>
/// <see cref="B"/>
/// </summary>
class Program
{
void B()
{
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(966633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/966633"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyNullableQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
{|SimplifyParent:Nullable<long>|}.Value x;
void M({|SimplifyParent:Nullable<int>|} a, ref {|SimplifyParent:System.Nullable<int>|} b, ref {|SimplifyParent:Nullable<long>|}.Something c) { }
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
Nullable<long>.Value x;
void M(int? a, ref int? b, ref Nullable<long>.Something c) { }
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(965240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965240"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyOpenGenericNullable() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof({|SimplifyParent:System.Nullable<>|});
var y = (typeof({|SimplifyParent:System.Nullable<long>|}));
var z = (typeof({|SimplifyParent:System.Nullable|}));
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var x = typeof(Nullable<>);
var y = (typeof(long?));
var z = (typeof(Nullable));
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(1067214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067214"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyTypeNameInExpressionBody_Property() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X => (Program)x;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(1067214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067214"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyTypeNameInExpressionBody_Method() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => ({|SimplifyParent:N.Program|})x;
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
namespace N
{
class Program
{
private object x;
public Program X() => (Program)x;
}
}]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyToPredefinedTypeNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new {|SimplifyParent:System.Int32|}.Blah;
}
}
}]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
namespace N
{
class Program
{
void Main()
{
var x = new Int32.Blah;
}
}
}]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DontSimplifyNullableInNameOfExpression() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof({|Simplify:Nullable<int>|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
void M()
{
var s = nameof(Nullable<int>);
}
}
]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsLHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
{|Simplify:this.i|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
this.i = 1;
}
}
]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsRHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
int x = {|Simplify:this.i|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
int x = this.i;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_AsMethodArgument_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M(int ii)
{
M({|Simplify:this.i|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M(int ii)
{
M(this.i);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i;
void M()
{
var s = {|Simplify:this.i|}.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i;
void M()
{
var s = this.i.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string s;
void M()
{
var x = {|Simplify:this.s|}?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string s;
void M()
{
var x = this.s?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsLHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
{|Simplify:this.i|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
this.i = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsRHS_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
int x = {|Simplify:this.i|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
int x = this.i;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_AsMethodArgument_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M(int ii)
{
M({|Simplify:this.i|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M(int ii)
{
M(this.i);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
var s = {|Simplify:this.i|}.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int i { get; set; }
void M()
{
var s = this.i.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string s { get; set; }
void M()
{
var x = {|Simplify:this.s|}?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string s { get; set; }
void M()
{
var x = this.s?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_AsVoidCallWithArguments_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
void M(int i)
{
{|Simplify:this.M|}(0);
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
void M(int i)
{
this.M(0);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_WithReturnType_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int M()
{
return {|Simplify:this.M|}();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int M()
{
return this.M();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_ChainedAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int M()
{
var s = {|Simplify:this.M|}().ToString();
return 0;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int M()
{
var s = this.M().ToString();
return 0;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_ConditionalAccess_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
string M()
{
return {|Simplify:this.M|}()?.ToString();
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
string M()
{
return this.M()?.ToString();
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithThis_EventSubscription_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
e += {|Simplify:this.Handler|};
e -= {|Simplify:this.Handler|};
e += new EventHandler({|Simplify:this.Handler|});
e -= new EventHandler({|Simplify:this.Handler|});
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
e += this.Handler;
e -= this.Handler;
e += new EventHandler(this.Handler);
e -= new EventHandler(this.Handler);
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithThis_AddAndRemoveHandler_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
{|Simplify:this.e|} += Handler;
{|Simplify:this.e|} -= Handler;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void Handler(object sender, EventArgs args)
{
this.e += Handler;
this.e -= Handler;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.CSharp))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithThis_InvokeEvent_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class C
{
event EventHandler e;
void OnSomeEvent()
{
{|Simplify:this.e|}(this, new EventArgs());
{|Simplify:this.e|}.Invoke(this, new EventArgs());
{|Simplify:this.e|}?.Invoke(this, new EventArgs());
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
using System;
class C
{
event EventHandler e;
void OnSomeEvent()
{
this.e(this, new EventArgs());
this.e.Invoke(this, new EventArgs());
this.e?.Invoke(this, new EventArgs());
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.CSharp))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessNotPresentOnNotificationOptionSilent_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Silent))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionInfo_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Suggestion))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionWarning_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Warning))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionError_CSharp() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
{|Simplify:this.Property|} = 1;
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
class C
{
int Property { get; set; }
void M()
{
this.Property = 1;
}
}
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Error))
End Function
#End Region
#Region "Normal Visual Basic Tests"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyTypeName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
Class A
Private e As {|SimplifyParent:System.Exception|}
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Private e As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Array_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Goo() As Integer
Sub Main(args As String())
{|SimplifyParent:Program|}.Goo(23) = 23
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Goo() As Integer
Sub Main(args As String())
Goo(23) = 23
End Sub
End Module
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Array_2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
{|SimplifyParent:Program.Bar|}(2)(2)
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Module Program
Dim Bar() As Action(Of Integer)
Sub Main(args As String())
Bar(2)(2)
End Sub
End Module
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:other.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
other.M(Nothing)
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M(other As C)
{|SimplifyParent:Me.M|}(Nothing)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class C
Sub M(other As C)
M(Nothing)
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(547117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547117")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestGetChanges_SimplifyTypeName_Receiver3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public Shared B As Action
Public Sub M(ab As A)
{|SimplifyParent:ab.B|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public Shared B As Action
Public Sub M(ab As A)
ab.B()
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim [Preserve].X.Y(1)
End Sub
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType2() As Task
' Simplified type is in a different namespace.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
NotInheritable Class M
Public Shared Sub Main()
ReDim N1.Preserve.X.Y(1)
End Sub
End Class</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType3() As Task
' Simplified type is in a different namespace, whose names have been imported with an Imports statement.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim P.NonGeneric.{|SimplifyParent:X|}.Y(1)
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1
Namespace N1
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
End Namespace
Namespace P
Class NonGeneric
Inherits N1.Preserve
End Class
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].X.Y(1)
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType4() As Task
' Highly nested type simplified to another highly nested type.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits N1.N2.Outer.Preserve
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = N1.N2.Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyNestedType5() As Task
' Name requiring multiple iterations of nested type simplification.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Generic(Of Integer).NonGenericInner.{|SimplifyParent:X|}.Y
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports N1.N2
Imports P1.P2
Imports Q1.Q2
Namespace N1
Namespace N2
Public Class Outer
Public Class Preserve
Public Class X
Public Shared Y As Integer
End Class
End Class
End Class
End Namespace
End Namespace
Namespace P1
Namespace P2
Public Class NonGeneric
Inherits Outer
Public Class NonGenericInner
Inherits Outer.Preserve
End Class
End Class
End Namespace
End Namespace
Namespace Q1
Namespace Q2
Class Generic(Of T)
Inherits NonGeneric
End Class
End Namespace
End Namespace
Namespace R
NotInheritable Class M
Public Shared Sub Main()
Dim k As Integer = Outer.Preserve.X.Y
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:Z(Of Single).Y(1)|}
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class Preserve
Public Shared Y
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As {|SimplifyParent:C.B|}
Return Nothing
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Public NotInheritable Class B
End Class
End Class
Class C
Inherits A
End Class
Namespace N1
NotInheritable Class M
Public Shared Function F() As A.B
Return Nothing
End Function
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyAllNodes_SimplifyAliasStaticMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim {|SimplifyParent:X.Y(1)|}
End Sub
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports X = NonGeneric
Class Preserve
Public Shared Y
End Class
Class NonGeneric
Inherits Preserve
End Class
Namespace N1
NotInheritable Class M
Public Shared Sub Main()
Redim [Preserve].Y(1)
End Sub
End Class
End Namespace</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate1_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Del|})
A.{|SimplifyParent:Del|}()
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Del()
End Sub
Class B
Delegate Sub Del()
Sub Boo()
Dim d As Del = New Del(AddressOf A.Del)
A.Del()
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyNot_Delegate2_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.{|SimplifyParent:Bar|})
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Class A
Shared Sub Bar()
End Sub
Class B
Delegate Sub Del()
Sub Bar()
End Sub
Sub Boo()
Dim d As Del = New Del(AddressOf A.Bar)
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
<WorkItem(570986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570986")>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Async Function TestSimplifyNot_Action_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Goo()
A.{|SimplifyParent:Bar|}(3)
End Sub
End Class
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class A
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Class B
Shared Bar As Action(Of Integer) = New Action(Of Integer)(Function(x) x + 1)
Sub Goo()
A.Bar(3)
End Sub
End Class
End Class
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplifyBaseInheritanceVB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
MustInherit Class A
Public MustOverride Sub Goo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Goo()
MyBase.{|SimplifyParent:Boo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
MustInherit Class A
Public MustOverride Sub Goo()
Public Sub Boo()
End Sub
End Class
Class B
Inherits A
Public Overrides Sub Goo()
Boo()
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(588099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/588099")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_EscapeReservedNamesInAttributes() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
<Global.Assembly.{|SimplifyParent:Goo|}>
Module Assembly
Class GooAttribute
Inherits Attribute
End Class
End Module
Module M
Class GooAttribute
Inherits Attribute
End Class
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
<[Assembly].Goo>
Module Assembly
Class GooAttribute
Inherits Attribute
End Class
End Module
Module M
Class GooAttribute
Inherits Attribute
End Class
End Module
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_OmitModuleNameInMemberAccess() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
goo.Program.{|SimplifyParent:Main|}(Nothing)
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
Namespace bar
Module b
Sub m()
goo.Main(Nothing)
End Sub
End Module
End Namespace
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_OmitModuleNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as goo.Program.{|SimplifyParent:C1|}
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<code>
Imports System
Namespace goo
Module Program
Sub Main(args As String())
End Sub
Class C1
End Class
End Module
End Namespace
Namespace bar
Module b
Sub m()
Dim x as goo.C1
End Sub
End Module
End Namespace
</code>
Await TestAsync(input, expected)
End Function
<WorkItem(601160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601160")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestExpandMultilineLambdaWithImports() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
{|Expand:Sub Main(args As String())
Task.Run(Sub()
Imports System
End Sub)
End Sub|}
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(input)
Dim hostDocument = workspace.Documents.Single()
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim root = Await document.GetSyntaxRootAsync()
For Each span In hostDocument.AnnotatedSpans("Expand")
Dim node = root.FindToken(span.Start).Parent.Parent
If TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).Statements.Single()
End If
Assert.True(TypeOf node Is ExpressionStatementSyntax)
Dim result = Await Simplifier.ExpandAsync(node, document)
Assert.NotEqual(0, result.ToString().Count)
Next
End Using
End Function
<WorkItem(609496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609496")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_DoNotReduceNamesInNamespaceDeclarations() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace System.{|SimplifyParent:Goo|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports System
Namespace System.Goo
End Namespace
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_EscapeAliasReplacementIfNeeded() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New System.Runtime.InteropServices.{|SimplifyParent:InAttribute|}() ' Simplify Type Name
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Imports [In] = System.Runtime.InteropServices.InAttribute
Module M
Dim x = New [In]() ' Simplify Type Name
End Module
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(608197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608197")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVB_NoNREForOmittedReceiverInWithBlock() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Sub M()
With New B()
Dim x = .P.{|SimplifyParent:MaxValue|}
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Public Class A
Public Sub M()
With New B()
Dim x = .P.MaxValue
End With
End Sub
End Class
Public Class B
Public Property P As Integer
End Class
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(639971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639971")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestBugFix639971_VisualBasic_FalseUnnecessaryBaseQualifier() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Public Function Bar() As String
Return MyBase.{|SimplifyParent:ToString|}()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
Class Z
Public Function Bar() As String
Return MyBase.ToString()
End Function
End Class
Class Y
Inherits Z
Public Overrides Function ToString() As String
Return ""
End Function
Public Sub Baz()
Console.WriteLine(New Y().Bar())
End Sub
End Class
</Code>
Await TestAsync(input, expected)
End Function
<WorkItem(639971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639971")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestBugFix639971_CSharp_FalseUnnecessaryBaseQualifier() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
public string InvokeBaseToString()
{
return base.{|SimplifyParent:ToString|}();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<Code>
using System;
class C
{
public string InvokeBaseToString()
{
return base.ToString();
}
}
class D : C
{
public override string ToString()
{
return "";
}
static void Main()
{
Console.WriteLine(new D().InvokeBaseToString());
}
}
</Code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWhenParentHasSimplifyAnnotation() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_MutuallyExclusive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System|}
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_Inclusive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
{|SpanToSimplify:Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As System.Exception
End Class|}
End Namespace
|}
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingPositive() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
Dim c As {|SpanToSimplify:System.Exception|}
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameWithExplicitSimplifySpan_OverlappingNegative() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Namespace Root
{|SimplifyParent:Class A
{|SpanToSimplify:Dim c|} As System.Exception
End Class|}
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Namespace Root
Class A
Dim c As System.Exception
End Class
End Namespace
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(769354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769354")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyTypeNameInCrefCausesConflict() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="{|SimplifyParent:Global.Base|}.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Base
Public Sub New(x As Integer)
End Sub
End Class
Class Derived : Inherits Base
''' <summary>
''' <see cref="Base.New(Integer)"/>
''' </summary>
''' <param name="x"></param>
Public Sub New(x As Integer)
MyBase.New(x)
End Sub
Public Sub Base(x As Integer)
End Sub
End Class]]>
</text>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification), WorkItem(864735, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864735")>
Public Async Function TestBugFix864735_VisualBasic_SimplifyNameInIncompleteIsExpression() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf {|SimplifyParent:C.F|} Is
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class C
Shared Public F As Integer
Shared Sub Main()
Console.WriteLine(TypeOf F Is
End Sub
End Class
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(813566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813566")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestSimplifyQualifiedCref() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
''' <summary>
''' <see cref="{|Simplify:System.Object|}"/>
''' </summary>
Class Program
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
''' <summary>
''' <see cref="Object"/>
''' </summary>
Class Program
End Class]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyToGenericName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C.D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Await TestAsync(input, expected)
End Function
<WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DoNotSimplifyToGenericName() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Sub Main(args As String())
{|SimplifyParent:C.D|}.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Imports System
Class Program
Sub Main(args As String())
C.D.F()
End Sub
End Class
Public Class C(Of T)
Public Class D
Public Shared Sub F()
End Sub
End Class
End Class
Public Class C
Inherits C(Of Integer)
End Class
]]>
</text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_TestDontSimplifyAllNodes_SimplifyNestedType() As Task
Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {}
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim {|SimplifyParent:Z(Of Integer).X.Y(1)|}
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class Preserve
Public Class X
Public Shared Y
End Class
End Class
Class Z(Of T)
Inherits Preserve
End Class
NotInheritable Class M
Public Shared Sub Main()
ReDim [Preserve].X.Y(1)
End Sub
End Class]]></text>
Await TestAsync(input, expected, simplificationOption)
End Function
<Fact, WorkItem(881746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881746"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_SimplyToAlias() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:Attribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(881746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881746"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyAlias() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<{|SimplifyParent:AttributeAttributeAttribute|}>
Class A
End Class]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Imports AttributeAttributeAttribute = AttributeAttribute
Class AttributeAttribute
Inherits Attribute
End Class
<AttributeAttributeAttribute>
Class A
End Class]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(966633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/966633"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyNullableQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as {|SimplifyParent:Nullable(Of Integer)|}.Value
End Sub
Sub M(a as {|SimplifyParent:Nullable(Of Integer)|}, byref b as {|SimplifyParent:System.Nullable(Of Integer)|}, byref c as {|SimplifyParent:Nullable(Of Integer)|}.Value)
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x as Nullable(Of Integer).Value
End Sub
Sub M(a as Integer?, byref b as Integer?, byref c as Nullable(Of Integer).Value)
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(965240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965240"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyOpenGenericNullable() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType({|SimplifyParent:System.Nullable(Of )|})
Dim y = (GetType({|SimplifyParent:System.Nullable(Of Long)|}))
Dim z = (GetType({|SimplifyParent:System.Nullable|}))
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = GetType(Nullable(Of ))
Dim y = (GetType(Long?))
Dim z = (GetType(Nullable))
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<WpfFact(Skip:="1019361"), WorkItem(1019361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019361"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_Bug1019361() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = {|SimplifyParent:N.A|}.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Module Program
Sub Main()
Dim x = N.A.X ' Simplify type name 'N.A'
Dim a As A = Nothing
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<Fact, WorkItem(2232, "https://github.com/dotnet/roslyn/issues/2232"), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyToPredefinedTypeNameInQualifiedName() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New {|SimplifyParent:System.Int32|}.Blah
End Sub
End Module]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Module Module1
Sub Main()
Dim x = New System.Int32.Blah
End Sub
End Module]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(4859, "https://github.com/dotnet/roslyn/issues/4859")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_DontSimplifyNullableInNameOfExpression() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf({|Simplify:Nullable(Of Integer)|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M()
Dim s = NameOf(Nullable(Of Integer))
End Sum
End Class
]]></text>
Await TestAsync(input, expected)
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsLHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
{|Simplify:Me.i|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Me.i = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsRHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim x = {|Simplify:Me.i|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim x = Me.i
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_AsMethodArgument_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M(ii As Integer)
M({|Simplify:Me.i|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M(ii As Integer)
M(Me.i)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim s = {|Simplify:Me.i|}.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim i As Integer
Sub M()
Dim s = Me.i.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyFieldAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Dim s As String
Sub M()
Dim x = {|Simplify:Me.s|}?.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Dim s As String
Sub M()
Dim x = Me.s?.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyFieldAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsLHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
{|Simplify:Me.i|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Me.i = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsRHS_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim x = {|Simplify:Me.i|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim x = Me.i
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_AsMethodArgument_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M(ii As Integer)
M({|Simplify:Me.i|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M(ii As Integer)
M(Me.i)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim s = {|Simplify:Me.i|}.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property i As Integer
Sub M()
Dim s = Me.i.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyPropertyAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property s As String
Sub M()
Dim x = {|Simplify:Me.s|}?.ToString()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property s As String
Sub M()
Dim x = Me.s?.ToString()
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_AsSubCallWithArguments_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Sub M(i As Integer)
{|Simplify:Me.M|}(0)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Sub M(i As Integer)
Me.M(0)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_WithReturnType_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As Integer
Return {|Simplify:Me.M|}()
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As Integer
Return Me.M()
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_ChainedAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As Integer
Dim s = {|Simplify:Me.M|}().ToString()
Return 0
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As Integer
Dim s = Me.M().ToString()
Return 0
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_ConditionalAccess_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Function M() As String
Return {|Simplify:Me.M|}()?.ToString()
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Function M() As String
Return Me.M()?.ToString()
End Function
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMethodAccessWithMe_EventSubscription_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler e, AddressOf {|Simplify:Me.Handler|}
RemoveHandler e, AddressOf {|Simplify:Me.Handler|}
AddHandler e, New EventHandler(AddressOf {|Simplify:Me.Handler|})
RemoveHandler e, New EventHandler(AddressOf {|Simplify:Me.Handler|})
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler e, AddressOf Me.Handler
RemoveHandler e, AddressOf Me.Handler
AddHandler e, New EventHandler(AddressOf Me.Handler)
RemoveHandler e, New EventHandler(AddressOf Me.Handler)
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
<WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyEventAccessWithMe_AddAndRemoveHandler_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler {|Simplify:Me.e|}, AddressOf Handler
RemoveHandler {|Simplify:Me.e|}, AddressOf Handler
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Event e As EventHandler
Sub Handler(sender As Object, args As EventArgs)
AddHandler Me.e, AddressOf Handler
RemoveHandler Me.e, AddressOf Handler
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyEventAccessOption(LanguageNames.VisualBasic))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessNotPresentOnNotificationOptionSilent_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Silent))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionInfo_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Suggestion))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionWarning_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Warning))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function QualifyMemberAccessOnNotificationOptionError_VisualBasic() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Class C
Property I As Integer
Sub M()
{|Simplify:Me.I|} = 1
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Class C
Property I As Integer
Sub M()
Me.I = 1
End Sub
End Class
]]>
</text>
Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Error))
End Function
<WorkItem(7955, "https://github.com/dotnet/roslyn/issues/7955")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function UsePredefinedTypeKeywordIfTextIsTheSame() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M(p As {|Simplify:[String]|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M(p As String)
End Sum
End Class
]]></text>
Await TestAsync(input, expected, DontPreferIntrinsicPredefinedTypeKeywordInDeclaration)
End Function
<WorkItem(7955, "https://github.com/dotnet/roslyn/issues/7955")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function DontUsePredefinedTypeKeyword() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class C
Sub M(p As {|Simplify:Int32|})
End Sum
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class C
Sub M(p As Int32)
End Sum
End Class
]]></text>
Await TestAsync(input, expected, DontPreferIntrinsicPredefinedTypeKeywordInDeclaration)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSharedMemberOffOfMe() As Task
' even if the user prefers qualified member access, we will strip off 'Me' when calling
' a static method through it.
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Imports System
Class Class1
Sub Main()
{|SimplifyParent:Me.Goo|}()
End Sub
Shared Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text>
<![CDATA[
Imports System
Class Class1
Sub Main()
Goo()
End Sub
Shared Sub Goo()
End Sub
End Class
]]></text>
Await TestAsync(input, expected, QualifyMethodAccessOption(LanguageNames.VisualBasic))
End Function
#End Region
#Region "Helpers"
Private Protected Shared Function QualifyFieldAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyPropertyAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return QualifyPropertyAccessOptionWithNotification(languageName, NotificationOption2.Error)
End Function
Private Protected Shared Function QualifyMethodAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyMethodAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyEventAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyEventAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}}
End Function
Private Protected Shared Function QualifyPropertyAccessOptionWithNotification(languageName As String, notification As NotificationOption2) As Dictionary(Of OptionKey2, Object)
Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyPropertyAccess, languageName), New CodeStyleOption2(Of Boolean)(True, notification)}}
End Function
Private Shared ReadOnly DontPreferIntrinsicPredefinedTypeKeywordInDeclaration As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic), CodeStyleOption2(Of Boolean).Default}}
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/Lowering/MethodToClassRewriter/MethodToClassRewriter.MyBaseMyClassWrapper.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy)
Private Function SubstituteMethodForMyBaseOrMyClassCall(receiverOpt As BoundExpression, originalMethodBeingCalled As MethodSymbol) As MethodSymbol
If (originalMethodBeingCalled.IsMetadataVirtual OrElse Me.IsInExpressionLambda) AndAlso
receiverOpt IsNot Nothing AndAlso (receiverOpt.Kind = BoundKind.MyBaseReference OrElse receiverOpt.Kind = BoundKind.MyClassReference) Then
' NOTE: We can only call a virtual method non-virtually if the type of Me reference
' we pass to this method IS or INHERITS FROM the type of the method we want to call;
'
' Thus, for MyBase/MyClass receivers we MAY need to replace
' the method with a wrapper one to be able to call it non-virtually;
'
Dim callingMethodType As TypeSymbol = Me.CurrentMethod.ContainingType
Dim topLevelMethodType As TypeSymbol = Me.TopLevelMethod.ContainingType
If callingMethodType IsNot topLevelMethodType OrElse Me.IsInExpressionLambda Then
Dim newMethod = GetOrCreateMyBaseOrMyClassWrapperFunction(receiverOpt, originalMethodBeingCalled)
' substitute type parameters if needed
If newMethod.IsGenericMethod Then
Debug.Assert(originalMethodBeingCalled.IsGenericMethod)
Dim typeArgs = originalMethodBeingCalled.TypeArguments
Debug.Assert(typeArgs.Length = newMethod.Arity)
Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol
For i = 0 To typeArgs.Length - 1
visitedTypeArgs(i) = VisitType(typeArgs(i))
Next
newMethod = newMethod.Construct(visitedTypeArgs.AsImmutableOrNull())
End If
Return newMethod
End If
End If
Return originalMethodBeingCalled
End Function
Private Function GetOrCreateMyBaseOrMyClassWrapperFunction(receiver As BoundExpression, method As MethodSymbol) As MethodSymbol
Debug.Assert(receiver IsNot Nothing)
Debug.Assert(receiver.IsMyClassReference() OrElse receiver.IsMyBaseReference())
Debug.Assert(method IsNot Nothing)
method = method.ConstructedFrom()
Dim methodWrapper As MethodSymbol = CompilationState.GetMethodWrapper(method)
If methodWrapper IsNot Nothing Then
Return methodWrapper
End If
' Disregarding what was passed as the receiver, we only need to create one wrapper
' method for a method _symbol_ being called. Thus, if topLevelMethod.ContainingType
' overrides the virtual method M1, 'MyClass.M1' will use a wrapper method for
' topLevelMethod.ContainingType.M1 method symbol and 'MyBase.M1' will use
' a wrapper method for topLevelMethod.ContainingType.BaseType.M1 method symbol.
' In case topLevelMethod.ContainingType DOES NOT override M1, both 'MyClass.M1' and
' 'MyBase.M1' will use a wrapper method for topLevelMethod.ContainingType.BaseType.M1.
Dim containingType As NamedTypeSymbol = Me.TopLevelMethod.ContainingType
Dim methodContainingType As NamedTypeSymbol = method.ContainingType
Dim isMyBase As Boolean = Not methodContainingType.Equals(containingType)
Debug.Assert(isMyBase OrElse receiver.Kind = BoundKind.MyClassReference)
Dim syntax As SyntaxNode = Me.CurrentMethod.Syntax
' generate and register wrapper method
Dim wrapperMethodName As String = GeneratedNames.MakeBaseMethodWrapperName(method.Name, isMyBase)
Dim wrapperMethod As New SynthesizedWrapperMethod(DirectCast(containingType, InstanceTypeSymbol), method, wrapperMethodName, syntax)
' register a new method
If Me.CompilationState.ModuleBuilderOpt IsNot Nothing Then
Me.CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(containingType, wrapperMethod.GetCciAdapter())
End If
' generate method body
Dim wrappedMethod As MethodSymbol = wrapperMethod.WrappedMethod
Debug.Assert(wrappedMethod.ConstructedFrom() Is method)
Dim boundArguments(wrapperMethod.ParameterCount - 1) As BoundExpression
For argIndex = 0 To wrapperMethod.ParameterCount - 1
Dim parameterSymbol As ParameterSymbol = wrapperMethod.Parameters(argIndex)
boundArguments(argIndex) = New BoundParameter(syntax, parameterSymbol, isLValue:=parameterSymbol.IsByRef, type:=parameterSymbol.Type)
Next
Dim meParameter As ParameterSymbol = wrapperMethod.MeParameter
Dim newReceiver As BoundExpression = Nothing
If isMyBase Then
newReceiver = New BoundMyBaseReference(syntax, meParameter.Type)
Else
newReceiver = New BoundMyClassReference(syntax, meParameter.Type)
End If
Dim boundCall As New BoundCall(syntax, wrappedMethod, Nothing, newReceiver,
boundArguments.AsImmutableOrNull, Nothing, wrappedMethod.ReturnType)
Dim boundMethodBody As BoundStatement = If(Not wrappedMethod.ReturnType.IsVoidType(),
DirectCast(New BoundReturnStatement(syntax, boundCall, Nothing, Nothing), BoundStatement),
New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(
New BoundExpressionStatement(syntax, boundCall),
New BoundReturnStatement(syntax, Nothing, Nothing, Nothing))))
' add to generated method collection and return
CompilationState.AddMethodWrapper(method, wrapperMethod, boundMethodBody)
Return wrapperMethod
End Function
''' <summary>
''' A method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <remarks>
''' <example>
''' Class A
''' Protected Overridable Sub F(a As Integer)
''' End Sub
''' End Class
'''
''' Class B
''' Inherits A
'''
''' Public Sub M()
''' Dim b As Integer = 1
''' Dim f As System.Action = Sub() MyBase.F(b)
''' End Sub
''' End Class
''' </example>
''' </remarks>
Friend NotInheritable Class SynthesizedWrapperMethod
Inherits SynthesizedMethod
Private ReadOnly _wrappedMethod As MethodSymbol
Private ReadOnly _typeMap As TypeSubstitution
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Private ReadOnly _locations As ImmutableArray(Of Location)
''' <summary>
''' Creates a symbol for a method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <param name="containingType">Type that contains wrapper method.</param>
''' <param name="methodToWrap">Method to wrap</param>
''' <param name="wrapperName">Wrapper method name</param>
''' <param name="syntax">Syntax node.</param>
Friend Sub New(containingType As InstanceTypeSymbol,
methodToWrap As MethodSymbol,
wrapperName As String,
syntax As SyntaxNode)
MyBase.New(syntax, containingType, wrapperName, False)
Me._locations = ImmutableArray.Create(Of Location)(syntax.GetLocation())
Me._typeMap = Nothing
If Not methodToWrap.IsGenericMethod Then
Me._typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty
Me._wrappedMethod = methodToWrap
Else
Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(methodToWrap.OriginalDefinition.TypeParameters, Me, CreateTypeParameter)
Dim typeArgs(Me._typeParameters.Length - 1) As TypeSymbol
For ind = 0 To Me._typeParameters.Length - 1
typeArgs(ind) = Me._typeParameters(ind)
Next
Dim newConstructedWrappedMethod As MethodSymbol = methodToWrap.Construct(typeArgs.AsImmutableOrNull())
Me._typeMap = TypeSubstitution.Create(newConstructedWrappedMethod.OriginalDefinition,
newConstructedWrappedMethod.OriginalDefinition.TypeParameters,
typeArgs.AsImmutableOrNull())
Me._wrappedMethod = newConstructedWrappedMethod
End If
Dim params(Me._wrappedMethod.ParameterCount - 1) As ParameterSymbol
For i = 0 To params.Length - 1
Dim curParam = Me._wrappedMethod.Parameters(i)
params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type.InternalSubstituteTypeParameters(Me._typeMap).Type, curParam)
Next
Me._parameters = params.AsImmutableOrNull()
Me._returnType = Me._wrappedMethod.ReturnType.InternalSubstituteTypeParameters(Me._typeMap).Type
End Sub
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me._typeMap
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
' Dev11 emits DebuggerNonUserCode. We emit DebuggerHidden to hide the method even if JustMyCode is off.
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute())
End Sub
Public ReadOnly Property WrappedMethod As MethodSymbol
Get
Return Me._wrappedMethod
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
' This is always a method definition, so the type arguments are the same as the type parameters.
If Arity > 0 Then
Return StaticCast(Of TypeSymbol).From(Me.TypeParameters)
Else
Return ImmutableArray(Of TypeSymbol).Empty
End If
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me._wrappedMethod.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Me._wrappedMethod.IsVararg
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
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
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy)
Private Function SubstituteMethodForMyBaseOrMyClassCall(receiverOpt As BoundExpression, originalMethodBeingCalled As MethodSymbol) As MethodSymbol
If (originalMethodBeingCalled.IsMetadataVirtual OrElse Me.IsInExpressionLambda) AndAlso
receiverOpt IsNot Nothing AndAlso (receiverOpt.Kind = BoundKind.MyBaseReference OrElse receiverOpt.Kind = BoundKind.MyClassReference) Then
' NOTE: We can only call a virtual method non-virtually if the type of Me reference
' we pass to this method IS or INHERITS FROM the type of the method we want to call;
'
' Thus, for MyBase/MyClass receivers we MAY need to replace
' the method with a wrapper one to be able to call it non-virtually;
'
Dim callingMethodType As TypeSymbol = Me.CurrentMethod.ContainingType
Dim topLevelMethodType As TypeSymbol = Me.TopLevelMethod.ContainingType
If callingMethodType IsNot topLevelMethodType OrElse Me.IsInExpressionLambda Then
Dim newMethod = GetOrCreateMyBaseOrMyClassWrapperFunction(receiverOpt, originalMethodBeingCalled)
' substitute type parameters if needed
If newMethod.IsGenericMethod Then
Debug.Assert(originalMethodBeingCalled.IsGenericMethod)
Dim typeArgs = originalMethodBeingCalled.TypeArguments
Debug.Assert(typeArgs.Length = newMethod.Arity)
Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol
For i = 0 To typeArgs.Length - 1
visitedTypeArgs(i) = VisitType(typeArgs(i))
Next
newMethod = newMethod.Construct(visitedTypeArgs.AsImmutableOrNull())
End If
Return newMethod
End If
End If
Return originalMethodBeingCalled
End Function
Private Function GetOrCreateMyBaseOrMyClassWrapperFunction(receiver As BoundExpression, method As MethodSymbol) As MethodSymbol
Debug.Assert(receiver IsNot Nothing)
Debug.Assert(receiver.IsMyClassReference() OrElse receiver.IsMyBaseReference())
Debug.Assert(method IsNot Nothing)
method = method.ConstructedFrom()
Dim methodWrapper As MethodSymbol = CompilationState.GetMethodWrapper(method)
If methodWrapper IsNot Nothing Then
Return methodWrapper
End If
' Disregarding what was passed as the receiver, we only need to create one wrapper
' method for a method _symbol_ being called. Thus, if topLevelMethod.ContainingType
' overrides the virtual method M1, 'MyClass.M1' will use a wrapper method for
' topLevelMethod.ContainingType.M1 method symbol and 'MyBase.M1' will use
' a wrapper method for topLevelMethod.ContainingType.BaseType.M1 method symbol.
' In case topLevelMethod.ContainingType DOES NOT override M1, both 'MyClass.M1' and
' 'MyBase.M1' will use a wrapper method for topLevelMethod.ContainingType.BaseType.M1.
Dim containingType As NamedTypeSymbol = Me.TopLevelMethod.ContainingType
Dim methodContainingType As NamedTypeSymbol = method.ContainingType
Dim isMyBase As Boolean = Not methodContainingType.Equals(containingType)
Debug.Assert(isMyBase OrElse receiver.Kind = BoundKind.MyClassReference)
Dim syntax As SyntaxNode = Me.CurrentMethod.Syntax
' generate and register wrapper method
Dim wrapperMethodName As String = GeneratedNames.MakeBaseMethodWrapperName(method.Name, isMyBase)
Dim wrapperMethod As New SynthesizedWrapperMethod(DirectCast(containingType, InstanceTypeSymbol), method, wrapperMethodName, syntax)
' register a new method
If Me.CompilationState.ModuleBuilderOpt IsNot Nothing Then
Me.CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(containingType, wrapperMethod.GetCciAdapter())
End If
' generate method body
Dim wrappedMethod As MethodSymbol = wrapperMethod.WrappedMethod
Debug.Assert(wrappedMethod.ConstructedFrom() Is method)
Dim boundArguments(wrapperMethod.ParameterCount - 1) As BoundExpression
For argIndex = 0 To wrapperMethod.ParameterCount - 1
Dim parameterSymbol As ParameterSymbol = wrapperMethod.Parameters(argIndex)
boundArguments(argIndex) = New BoundParameter(syntax, parameterSymbol, isLValue:=parameterSymbol.IsByRef, type:=parameterSymbol.Type)
Next
Dim meParameter As ParameterSymbol = wrapperMethod.MeParameter
Dim newReceiver As BoundExpression = Nothing
If isMyBase Then
newReceiver = New BoundMyBaseReference(syntax, meParameter.Type)
Else
newReceiver = New BoundMyClassReference(syntax, meParameter.Type)
End If
Dim boundCall As New BoundCall(syntax, wrappedMethod, Nothing, newReceiver,
boundArguments.AsImmutableOrNull, Nothing, wrappedMethod.ReturnType)
Dim boundMethodBody As BoundStatement = If(Not wrappedMethod.ReturnType.IsVoidType(),
DirectCast(New BoundReturnStatement(syntax, boundCall, Nothing, Nothing), BoundStatement),
New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(
New BoundExpressionStatement(syntax, boundCall),
New BoundReturnStatement(syntax, Nothing, Nothing, Nothing))))
' add to generated method collection and return
CompilationState.AddMethodWrapper(method, wrapperMethod, boundMethodBody)
Return wrapperMethod
End Function
''' <summary>
''' A method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <remarks>
''' <example>
''' Class A
''' Protected Overridable Sub F(a As Integer)
''' End Sub
''' End Class
'''
''' Class B
''' Inherits A
'''
''' Public Sub M()
''' Dim b As Integer = 1
''' Dim f As System.Action = Sub() MyBase.F(b)
''' End Sub
''' End Class
''' </example>
''' </remarks>
Friend NotInheritable Class SynthesizedWrapperMethod
Inherits SynthesizedMethod
Private ReadOnly _wrappedMethod As MethodSymbol
Private ReadOnly _typeMap As TypeSubstitution
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Private ReadOnly _locations As ImmutableArray(Of Location)
''' <summary>
''' Creates a symbol for a method that wraps the call to a method through MyBase/MyClass receiver.
''' </summary>
''' <param name="containingType">Type that contains wrapper method.</param>
''' <param name="methodToWrap">Method to wrap</param>
''' <param name="wrapperName">Wrapper method name</param>
''' <param name="syntax">Syntax node.</param>
Friend Sub New(containingType As InstanceTypeSymbol,
methodToWrap As MethodSymbol,
wrapperName As String,
syntax As SyntaxNode)
MyBase.New(syntax, containingType, wrapperName, False)
Me._locations = ImmutableArray.Create(Of Location)(syntax.GetLocation())
Me._typeMap = Nothing
If Not methodToWrap.IsGenericMethod Then
Me._typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty
Me._wrappedMethod = methodToWrap
Else
Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(methodToWrap.OriginalDefinition.TypeParameters, Me, CreateTypeParameter)
Dim typeArgs(Me._typeParameters.Length - 1) As TypeSymbol
For ind = 0 To Me._typeParameters.Length - 1
typeArgs(ind) = Me._typeParameters(ind)
Next
Dim newConstructedWrappedMethod As MethodSymbol = methodToWrap.Construct(typeArgs.AsImmutableOrNull())
Me._typeMap = TypeSubstitution.Create(newConstructedWrappedMethod.OriginalDefinition,
newConstructedWrappedMethod.OriginalDefinition.TypeParameters,
typeArgs.AsImmutableOrNull())
Me._wrappedMethod = newConstructedWrappedMethod
End If
Dim params(Me._wrappedMethod.ParameterCount - 1) As ParameterSymbol
For i = 0 To params.Length - 1
Dim curParam = Me._wrappedMethod.Parameters(i)
params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type.InternalSubstituteTypeParameters(Me._typeMap).Type, curParam)
Next
Me._parameters = params.AsImmutableOrNull()
Me._returnType = Me._wrappedMethod.ReturnType.InternalSubstituteTypeParameters(Me._typeMap).Type
End Sub
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me._typeMap
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = Me.DeclaringCompilation
AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
' Dev11 emits DebuggerNonUserCode. We emit DebuggerHidden to hide the method even if JustMyCode is off.
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute())
End Sub
Public ReadOnly Property WrappedMethod As MethodSymbol
Get
Return Me._wrappedMethod
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
' This is always a method definition, so the type arguments are the same as the type parameters.
If Arity > 0 Then
Return StaticCast(Of TypeSymbol).From(Me.TypeParameters)
Else
Return ImmutableArray(Of TypeSymbol).Empty
End If
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Me._wrappedMethod.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return Me._wrappedMethod.IsVararg
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Tools/ExternalAccess/FSharp/Editor/FSharpNavigationBarItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor
{
internal class FSharpNavigationBarItem
{
public string Text { get; }
public FSharpGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public IList<FSharpNavigationBarItem> ChildItems { get; }
public IList<TextSpan> Spans { get; internal set; }
internal IList<ITrackingSpan> TrackingSpans { get; set; }
public FSharpNavigationBarItem(
string text,
FSharpGlyph glyph,
IList<TextSpan> spans,
IList<FSharpNavigationBarItem> childItems = null,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans;
this.ChildItems = childItems ?? SpecializedCollections.EmptyList<FSharpNavigationBarItem>();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor
{
internal class FSharpNavigationBarItem
{
public string Text { get; }
public FSharpGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public IList<FSharpNavigationBarItem> ChildItems { get; }
public IList<TextSpan> Spans { get; internal set; }
internal IList<ITrackingSpan> TrackingSpans { get; set; }
public FSharpNavigationBarItem(
string text,
FSharpGlyph glyph,
IList<TextSpan> spans,
IList<FSharpNavigationBarItem> childItems = null,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans;
this.ChildItems = childItems ?? SpecializedCollections.EmptyList<FSharpNavigationBarItem>();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureServiceWithProviders : BlockStructureService
{
private readonly Workspace _workspace;
private readonly ImmutableArray<BlockStructureProvider> _providers;
protected BlockStructureServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_providers = GetBuiltInProviders().Concat(GetImportedProviders());
}
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders()
=> ImmutableArray<BlockStructureProvider>.Empty;
private ImmutableArray<BlockStructureProvider> GetImportedProviders()
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>()
.Where(lz => lz.Metadata.Language == language)
.Select(lz => lz.Value);
return providers.ToImmutableArray();
}
public override async Task<BlockStructure> GetBlockStructureAsync(
Document document,
CancellationToken cancellationToken)
{
var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false);
return GetBlockStructure(context, _providers);
}
public BlockStructure GetBlockStructure(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
return GetBlockStructure(context, _providers);
}
private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var options = document.Project.Solution.Options;
var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource;
return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
}
private static BlockStructureContext CreateContext(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource);
return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken);
}
private static BlockStructure GetBlockStructure(
BlockStructureContext context,
ImmutableArray<BlockStructureProvider> providers)
{
foreach (var provider in providers)
provider.ProvideBlockStructure(context);
return CreateBlockStructure(context);
}
private static BlockStructure CreateBlockStructure(BlockStructureContext context)
{
var language = context.SyntaxTree.Options.Language;
var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language);
var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language);
var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language);
var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language);
var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language);
var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language);
using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans);
foreach (var span in context.Spans)
{
var updatedSpan = UpdateBlockSpan(span,
showIndentGuidesForCodeLevelConstructs,
showIndentGuidesForDeclarationLevelConstructs,
showIndentGuidesForCommentsAndPreprocessorRegions,
showOutliningForCodeLevelConstructs,
showOutliningForDeclarationLevelConstructs,
showOutliningForCommentsAndPreprocessorRegions);
updatedSpans.Add(updatedSpan);
}
return new BlockStructure(updatedSpans.ToImmutable());
}
private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan,
bool showIndentGuidesForCodeLevelConstructs,
bool showIndentGuidesForDeclarationLevelConstructs,
bool showIndentGuidesForCommentsAndPreprocessorRegions,
bool showOutliningForCodeLevelConstructs,
bool showOutliningForDeclarationLevelConstructs,
bool showOutliningForCommentsAndPreprocessorRegions)
{
var type = blockSpan.Type;
var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type);
var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type);
var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type);
if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) ||
(!showIndentGuidesForCodeLevelConstructs && isMemberLevel) ||
(!showIndentGuidesForCommentsAndPreprocessorRegions && isComment))
{
type = BlockTypes.Nonstructural;
}
var isCollapsible = blockSpan.IsCollapsible;
if (isCollapsible)
{
if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) ||
(!showOutliningForCodeLevelConstructs && isMemberLevel) ||
(!showOutliningForCommentsAndPreprocessorRegions && isComment))
{
isCollapsible = false;
}
}
return blockSpan.With(type: type, isCollapsible: isCollapsible);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureServiceWithProviders : BlockStructureService
{
private readonly Workspace _workspace;
private readonly ImmutableArray<BlockStructureProvider> _providers;
protected BlockStructureServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_providers = GetBuiltInProviders().Concat(GetImportedProviders());
}
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders()
=> ImmutableArray<BlockStructureProvider>.Empty;
private ImmutableArray<BlockStructureProvider> GetImportedProviders()
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>()
.Where(lz => lz.Metadata.Language == language)
.Select(lz => lz.Value);
return providers.ToImmutableArray();
}
public override async Task<BlockStructure> GetBlockStructureAsync(
Document document,
CancellationToken cancellationToken)
{
var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false);
return GetBlockStructure(context, _providers);
}
public BlockStructure GetBlockStructure(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
return GetBlockStructure(context, _providers);
}
private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var options = document.Project.Solution.Options;
var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource;
return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
}
private static BlockStructureContext CreateContext(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource);
return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken);
}
private static BlockStructure GetBlockStructure(
BlockStructureContext context,
ImmutableArray<BlockStructureProvider> providers)
{
foreach (var provider in providers)
provider.ProvideBlockStructure(context);
return CreateBlockStructure(context);
}
private static BlockStructure CreateBlockStructure(BlockStructureContext context)
{
var language = context.SyntaxTree.Options.Language;
var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language);
var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language);
var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language);
var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language);
var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language);
var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language);
using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans);
foreach (var span in context.Spans)
{
var updatedSpan = UpdateBlockSpan(span,
showIndentGuidesForCodeLevelConstructs,
showIndentGuidesForDeclarationLevelConstructs,
showIndentGuidesForCommentsAndPreprocessorRegions,
showOutliningForCodeLevelConstructs,
showOutliningForDeclarationLevelConstructs,
showOutliningForCommentsAndPreprocessorRegions);
updatedSpans.Add(updatedSpan);
}
return new BlockStructure(updatedSpans.ToImmutable());
}
private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan,
bool showIndentGuidesForCodeLevelConstructs,
bool showIndentGuidesForDeclarationLevelConstructs,
bool showIndentGuidesForCommentsAndPreprocessorRegions,
bool showOutliningForCodeLevelConstructs,
bool showOutliningForDeclarationLevelConstructs,
bool showOutliningForCommentsAndPreprocessorRegions)
{
var type = blockSpan.Type;
var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type);
var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type);
var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type);
if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) ||
(!showIndentGuidesForCodeLevelConstructs && isMemberLevel) ||
(!showIndentGuidesForCommentsAndPreprocessorRegions && isComment))
{
type = BlockTypes.Nonstructural;
}
var isCollapsible = blockSpan.IsCollapsible;
if (isCollapsible)
{
if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) ||
(!showOutliningForCodeLevelConstructs && isMemberLevel) ||
(!showOutliningForCommentsAndPreprocessorRegions && isComment))
{
isCollapsible = false;
}
}
return blockSpan.With(type: type, isCollapsible: isCollapsible);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/GenericsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers
{
[CompilerTrait(CompilerFeature.ModuleInitializers)]
public sealed class GenericsTests : CSharpTestBase
{
private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9;
[Fact]
public void MustNotBeGenericMethod()
{
string source = @"
using System.Runtime.CompilerServices;
class C
{
[ModuleInitializer]
internal static void M<T>() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeContainedInGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
[ModuleInitializer]
internal static void M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeGenericAndContainedInGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
[ModuleInitializer]
internal static void M<U>() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8816: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeContainedInGenericTypeWithParametersDeclaredByContainingGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
internal class Nested
{
[ModuleInitializer]
internal static void M() { }
}
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (8,10): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(8, 10)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers
{
[CompilerTrait(CompilerFeature.ModuleInitializers)]
public sealed class GenericsTests : CSharpTestBase
{
private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9;
[Fact]
public void MustNotBeGenericMethod()
{
string source = @"
using System.Runtime.CompilerServices;
class C
{
[ModuleInitializer]
internal static void M<T>() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeContainedInGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
[ModuleInitializer]
internal static void M() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeGenericAndContainedInGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
[ModuleInitializer]
internal static void M<U>() { }
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (6,6): error CS8816: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(6, 6)
);
}
[Fact]
public void MustNotBeContainedInGenericTypeWithParametersDeclaredByContainingGenericType()
{
string source = @"
using System.Runtime.CompilerServices;
class C<T>
{
internal class Nested
{
[ModuleInitializer]
internal static void M() { }
}
}
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
";
var compilation = CreateCompilation(source, parseOptions: s_parseOptions);
compilation.VerifyEmitDiagnostics(
// (8,10): error CS8798: Module initializer method 'M' must not be generic and must not be contained in a generic type
// [ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric, "ModuleInitializer").WithArguments("M").WithLocation(8, 10)
);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class FormattingEngineTests : CSharpFormattingEngineTestBase
{
public FormattingEngineTests(ITestOutputHelper output) : base(output) { }
private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping()
{
return new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart },
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false },
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false },
};
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithView(expected, code);
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentPasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true);
}
[WpfFact]
[WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentReadOnlyWorkspacePasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatUsingStatementWhenTypingCloseParen()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)
}
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatNotUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine()
{
var code = @"class C
{
public void M()
{
if (true) {$$
}
}";
var expected = @"class C
{
public void M()
{
if (true) {
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine()
{
var code = @"class C
{
public void M()
{
if (true)
{$$
}
}";
var expected = @"class C
{
public void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatPragmaWarningInbetweenDelegateDeclarationStatement()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
Func <bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
Func<bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashEndRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansIndividuallyWithoutCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
if(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if(true){}
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansWithCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
while(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
while (true) { }
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true)));
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SemicolonInCommentOnLastLineDoesNotFormat()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;$$";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_1()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_2()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_1()
{
var code = @"class Program
{
static void Main(int a/* {$$ */, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* { */, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_2()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_3()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_1()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_2()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_1()
{
var code = @"class Program
{
/** {$$ **/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** { **/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_2()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_3()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideInactiveCode()
{
var code = @"class Program
{
#if false
{$$
#endif
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#if false
{
#endif
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideStringLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{$$"" ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{"" ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCharLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = '{$$' ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = '{' ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCommentsOfPreprocessorDirectives()
{
var code = @"class Program
{
#region
#endregion // a/*{$$*/
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#region
#endregion // a/*{*/
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1 :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInDefaultSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInPatternSwitchCase01()
{
var code = @"class Program
{
static void Main()
{
switch(f)
{
case int i :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main()
{
switch(f)
{
case int i: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInLabeledStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
label1 :$$ int s = 0;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
label1: int s = 0;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTargetAttribute()
{
var code = @"using System;
[method :$$ C]
class C : Attribute
{
}";
var expected = @"using System;
[method : C]
class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInBaseList()
{
var code = @"class C :$$ Attribute
{
}";
var expected = @"class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInThisConstructor()
{
var code = @"class Goo
{
Goo(int s) :$$ this()
{
}
Goo()
{
}
}";
var expected = @"class Goo
{
Goo(int s) : this()
{
}
Goo()
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInConditionalOperator()
{
var code = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true :$$ false;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true : false;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInArgument()
{
var code = @"class Program
{
static void Main(string[] args)
{
Main(args :$$ args);
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
Main(args : args);
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTypeParameter()
{
var code = @"class Program<T>
{
class C1<U>
where T :$$ U
{
}
}";
var expected = @"class Program<T>
{
class C1<U>
where T : U
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DontSmartFormatBracesOnSmartIndentNone()
{
var code = @"class Program<T>
{
class C1<U>
{$$
}";
var expected = @"class Program<T>
{
class C1<U>
{
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoIndentCloseBraceWhenFormatOnTypingIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void KeepTabsInCommentsWhenFormattingIsOff()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotKeepTabsInCommentsWhenFormattingIsOn()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code = @"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfSemicolonOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfTypingOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyNotFormattedIfNotAtStartOfLine()
{
var code =
@"
class C
{
public int P {$$
}
";
var expected =
@"
class C
{
public int P {
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyFormattedIfAtStartOfLine()
{
var code =
@"
class C
{
public int P
{$$
}
";
var expected =
@"
class C
{
public int P
{
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}$$";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;$$
x.ToString();
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}$$
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch
{
return;
x.ToString();
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatArbitraryNodeParenthesizedLambdaExpression()
{
// code equivalent to an expression synthesized like so:
// ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block()))
var code = @"(()=>{})";
var node = SyntaxFactory.ParseExpression(code);
var expected = @"(() => { })";
AssertFormatOnArbitraryNode(node, expected);
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2()
{
var code =
@"class Program
{
void M()
{
if (true)
{}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true )
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true )
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true ){$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true ){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7()
{
var code =
@"class Program
{
void M()
{$$
}";
var expected =
@"class Program
{
void M()
{
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2()
{
// Note that the { is not updated since we are not formatting.
var code =
@"class Program
{
void M()
{
if (true) {
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true) {
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3()
{
var code =
@"class Program
{
void M()
{
}$$
}";
var expected =
@"class Program
{
void M()
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4()
{
// Should not affect formatting of open brace
var code =
@"class Program
{
void M() {
}$$
}";
var expected =
@"class Program
{
void M() {
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")]
public async Task NullableReferenceTypes()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType;
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType;
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatGeneratedNodeInInitializer()
{
var code = @"new bool[] {
true,
true
}";
var expected = @"new bool[] {
true,
true == false, true
}";
var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script);
var root = tree.GetRoot();
var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry });
AssertFormatOnArbitraryNode(newRoot, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")]
public async Task PositionalPattern()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var point = new Point (3, 4);
if (point is Point (3, 4) _
&& point is Point{x: 3, y: 4} _)
{
}
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var point = new Point(3, 4);
if (point is Point(3, 4) _
&& point is Point { x: 3, y: 4 } _)
{
}
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression()
{
var code = @"[|
record C(int Property)
{
void M()
{
_ = this with { Property = 1 } ;
}
}
|]";
var expected = @"
record C(int Property)
{
void M()
{
_ = this with { Property = 1 };
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine_UserPositionedBraces()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace()
{
var code = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_DoNotGroupIfNotSorted()
{
var code = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
var expected = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst()
{
var code = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
var expected = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")]
public void PreserveAnnotationsOnMultiLineTrivia()
{
var text = @"
namespace TestApp
{
class Test
{
/* __marker__ */
}
}
";
var position = text.IndexOf("/* __marker__ */");
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = syntaxTree.GetRoot();
var annotation = new SyntaxAnnotation("marker");
var markerTrivia = root.FindTrivia(position, findInsideTrivia: true);
var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation);
root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia);
var formattedRoot = Formatter.Format(root, new AdhocWorkspace());
var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker");
Assert.Single(annotatedTrivia);
}
private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null)
{
using var workspace = TestWorkspace.CreateCSharp(code);
if (changedOptionSet != null)
{
var options = workspace.Options;
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
}
var subjectDocument = workspace.Documents.Single();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1);
commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create());
var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
Assert.Equal(expected, newSnapshot.GetText());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class FormattingEngineTests : CSharpFormattingEngineTestBase
{
public FormattingEngineTests(ITestOutputHelper output) : base(output) { }
private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping()
{
return new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart },
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false },
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false },
};
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithView(expected, code);
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentPasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true);
}
[WpfFact]
[WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentReadOnlyWorkspacePasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatUsingStatementWhenTypingCloseParen()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)
}
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatNotUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine()
{
var code = @"class C
{
public void M()
{
if (true) {$$
}
}";
var expected = @"class C
{
public void M()
{
if (true) {
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine()
{
var code = @"class C
{
public void M()
{
if (true)
{$$
}
}";
var expected = @"class C
{
public void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatPragmaWarningInbetweenDelegateDeclarationStatement()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
Func <bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
Func<bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashEndRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansIndividuallyWithoutCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
if(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if(true){}
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansWithCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
while(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
while (true) { }
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true)));
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SemicolonInCommentOnLastLineDoesNotFormat()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;$$";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_1()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_2()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_1()
{
var code = @"class Program
{
static void Main(int a/* {$$ */, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* { */, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_2()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_3()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_1()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_2()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_1()
{
var code = @"class Program
{
/** {$$ **/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** { **/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_2()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_3()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideInactiveCode()
{
var code = @"class Program
{
#if false
{$$
#endif
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#if false
{
#endif
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideStringLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{$$"" ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{"" ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCharLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = '{$$' ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = '{' ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCommentsOfPreprocessorDirectives()
{
var code = @"class Program
{
#region
#endregion // a/*{$$*/
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#region
#endregion // a/*{*/
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1 :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInDefaultSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInPatternSwitchCase01()
{
var code = @"class Program
{
static void Main()
{
switch(f)
{
case int i :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main()
{
switch(f)
{
case int i: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInLabeledStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
label1 :$$ int s = 0;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
label1: int s = 0;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTargetAttribute()
{
var code = @"using System;
[method :$$ C]
class C : Attribute
{
}";
var expected = @"using System;
[method : C]
class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInBaseList()
{
var code = @"class C :$$ Attribute
{
}";
var expected = @"class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInThisConstructor()
{
var code = @"class Goo
{
Goo(int s) :$$ this()
{
}
Goo()
{
}
}";
var expected = @"class Goo
{
Goo(int s) : this()
{
}
Goo()
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInConditionalOperator()
{
var code = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true :$$ false;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true : false;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInArgument()
{
var code = @"class Program
{
static void Main(string[] args)
{
Main(args :$$ args);
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
Main(args : args);
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTypeParameter()
{
var code = @"class Program<T>
{
class C1<U>
where T :$$ U
{
}
}";
var expected = @"class Program<T>
{
class C1<U>
where T : U
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DontSmartFormatBracesOnSmartIndentNone()
{
var code = @"class Program<T>
{
class C1<U>
{$$
}";
var expected = @"class Program<T>
{
class C1<U>
{
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoIndentCloseBraceWhenFormatOnTypingIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void KeepTabsInCommentsWhenFormattingIsOff()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotKeepTabsInCommentsWhenFormattingIsOn()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code = @"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfSemicolonOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfTypingOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyNotFormattedIfNotAtStartOfLine()
{
var code =
@"
class C
{
public int P {$$
}
";
var expected =
@"
class C
{
public int P {
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyFormattedIfAtStartOfLine()
{
var code =
@"
class C
{
public int P
{$$
}
";
var expected =
@"
class C
{
public int P
{
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}$$";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;$$
x.ToString();
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}$$
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch
{
return;
x.ToString();
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatArbitraryNodeParenthesizedLambdaExpression()
{
// code equivalent to an expression synthesized like so:
// ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block()))
var code = @"(()=>{})";
var node = SyntaxFactory.ParseExpression(code);
var expected = @"(() => { })";
AssertFormatOnArbitraryNode(node, expected);
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2()
{
var code =
@"class Program
{
void M()
{
if (true)
{}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true )
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true )
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true ){$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true ){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7()
{
var code =
@"class Program
{
void M()
{$$
}";
var expected =
@"class Program
{
void M()
{
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2()
{
// Note that the { is not updated since we are not formatting.
var code =
@"class Program
{
void M()
{
if (true) {
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true) {
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3()
{
var code =
@"class Program
{
void M()
{
}$$
}";
var expected =
@"class Program
{
void M()
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4()
{
// Should not affect formatting of open brace
var code =
@"class Program
{
void M() {
}$$
}";
var expected =
@"class Program
{
void M() {
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")]
public async Task NullableReferenceTypes()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType;
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType;
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatGeneratedNodeInInitializer()
{
var code = @"new bool[] {
true,
true
}";
var expected = @"new bool[] {
true,
true == false, true
}";
var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script);
var root = tree.GetRoot();
var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry });
AssertFormatOnArbitraryNode(newRoot, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")]
public async Task PositionalPattern()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var point = new Point (3, 4);
if (point is Point (3, 4) _
&& point is Point{x: 3, y: 4} _)
{
}
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var point = new Point(3, 4);
if (point is Point(3, 4) _
&& point is Point { x: 3, y: 4 } _)
{
}
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression()
{
var code = @"[|
record C(int Property)
{
void M()
{
_ = this with { Property = 1 } ;
}
}
|]";
var expected = @"
record C(int Property)
{
void M()
{
_ = this with { Property = 1 };
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine_UserPositionedBraces()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace()
{
var code = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_DoNotGroupIfNotSorted()
{
var code = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
var expected = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst()
{
var code = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
var expected = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")]
public void PreserveAnnotationsOnMultiLineTrivia()
{
var text = @"
namespace TestApp
{
class Test
{
/* __marker__ */
}
}
";
var position = text.IndexOf("/* __marker__ */");
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = syntaxTree.GetRoot();
var annotation = new SyntaxAnnotation("marker");
var markerTrivia = root.FindTrivia(position, findInsideTrivia: true);
var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation);
root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia);
var formattedRoot = Formatter.Format(root, new AdhocWorkspace());
var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker");
Assert.Single(annotatedTrivia);
}
private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null)
{
using var workspace = TestWorkspace.CreateCSharp(code);
if (changedOptionSet != null)
{
var options = workspace.Options;
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
}
var subjectDocument = workspace.Documents.Single();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1);
commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create());
var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
Assert.Equal(expected, newSnapshot.GetText());
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/CSharpTest/EditAndContinue/SyntaxComparerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class SyntaxComparerTests
{
private static SyntaxNode MakeLiteral(int n)
=> SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(n));
[Fact]
public void GetSequenceEdits1()
{
var edits = SyntaxComparer.GetSequenceEdits(
new[] { MakeLiteral(0), MakeLiteral(1), MakeLiteral(2) },
new[] { MakeLiteral(1), MakeLiteral(3) });
AssertEx.Equal(new[]
{
new SequenceEdit(2, -1),
new SequenceEdit(-1, 1),
new SequenceEdit(1, 0),
new SequenceEdit(0, -1),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits2()
{
var edits = SyntaxComparer.GetSequenceEdits(
ImmutableArray.Create(MakeLiteral(0), MakeLiteral(1), MakeLiteral(2)),
ImmutableArray.Create(MakeLiteral(1), MakeLiteral(3)));
AssertEx.Equal(new[]
{
new SequenceEdit(2, -1),
new SequenceEdit(-1, 1),
new SequenceEdit(1, 0),
new SequenceEdit(0, -1),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits3()
{
var edits = SyntaxComparer.GetSequenceEdits(
new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) },
new[] { SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) });
AssertEx.Equal(new[]
{
new SequenceEdit(2, 2),
new SequenceEdit(1, -1),
new SequenceEdit(0, 1),
new SequenceEdit(-1, 0),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits4()
{
var edits = SyntaxComparer.GetSequenceEdits(
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)),
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
AssertEx.Equal(new[]
{
new SequenceEdit(2, 2),
new SequenceEdit(1, -1),
new SequenceEdit(0, 1),
new SequenceEdit(-1, 0),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void ComputeDistance1()
{
var distance = SyntaxComparer.ComputeDistance(
new[] { MakeLiteral(0), MakeLiteral(1), MakeLiteral(2) },
new[] { MakeLiteral(1), MakeLiteral(3) });
Assert.Equal(0.67, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance2()
{
var distance = SyntaxComparer.ComputeDistance(
ImmutableArray.Create(MakeLiteral(0), MakeLiteral(1), MakeLiteral(2)),
ImmutableArray.Create(MakeLiteral(1), MakeLiteral(3)));
Assert.Equal(0.67, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance3()
{
var distance = SyntaxComparer.ComputeDistance(
new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) },
new[] { SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) });
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance4()
{
var distance = SyntaxComparer.ComputeDistance(
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)),
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Token()
{
var distance = SyntaxComparer.ComputeDistance(SyntaxFactory.Literal("abc", "abc"), SyntaxFactory.Literal("acb", "acb"));
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Node()
{
var distance = SyntaxComparer.ComputeDistance(MakeLiteral(101), MakeLiteral(150));
Assert.Equal(1, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Null()
{
var distance = SyntaxComparer.ComputeDistance(
default,
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword)));
Assert.Equal(1, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
default,
ImmutableArray.Create(MakeLiteral(0)));
Assert.Equal(1, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
null,
Array.Empty<SyntaxNode>());
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
Array.Empty<SyntaxNode>(),
null);
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
null,
Array.Empty<SyntaxToken>());
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
Array.Empty<SyntaxToken>(),
null);
Assert.Equal(0, Math.Round(distance, 2));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class SyntaxComparerTests
{
private static SyntaxNode MakeLiteral(int n)
=> SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(n));
[Fact]
public void GetSequenceEdits1()
{
var edits = SyntaxComparer.GetSequenceEdits(
new[] { MakeLiteral(0), MakeLiteral(1), MakeLiteral(2) },
new[] { MakeLiteral(1), MakeLiteral(3) });
AssertEx.Equal(new[]
{
new SequenceEdit(2, -1),
new SequenceEdit(-1, 1),
new SequenceEdit(1, 0),
new SequenceEdit(0, -1),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits2()
{
var edits = SyntaxComparer.GetSequenceEdits(
ImmutableArray.Create(MakeLiteral(0), MakeLiteral(1), MakeLiteral(2)),
ImmutableArray.Create(MakeLiteral(1), MakeLiteral(3)));
AssertEx.Equal(new[]
{
new SequenceEdit(2, -1),
new SequenceEdit(-1, 1),
new SequenceEdit(1, 0),
new SequenceEdit(0, -1),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits3()
{
var edits = SyntaxComparer.GetSequenceEdits(
new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) },
new[] { SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) });
AssertEx.Equal(new[]
{
new SequenceEdit(2, 2),
new SequenceEdit(1, -1),
new SequenceEdit(0, 1),
new SequenceEdit(-1, 0),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void GetSequenceEdits4()
{
var edits = SyntaxComparer.GetSequenceEdits(
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)),
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
AssertEx.Equal(new[]
{
new SequenceEdit(2, 2),
new SequenceEdit(1, -1),
new SequenceEdit(0, 1),
new SequenceEdit(-1, 0),
}, edits, itemInspector: e => e.GetTestAccessor().GetDebuggerDisplay());
}
[Fact]
public void ComputeDistance1()
{
var distance = SyntaxComparer.ComputeDistance(
new[] { MakeLiteral(0), MakeLiteral(1), MakeLiteral(2) },
new[] { MakeLiteral(1), MakeLiteral(3) });
Assert.Equal(0.67, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance2()
{
var distance = SyntaxComparer.ComputeDistance(
ImmutableArray.Create(MakeLiteral(0), MakeLiteral(1), MakeLiteral(2)),
ImmutableArray.Create(MakeLiteral(1), MakeLiteral(3)));
Assert.Equal(0.67, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance3()
{
var distance = SyntaxComparer.ComputeDistance(
new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) },
new[] { SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword) });
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance4()
{
var distance = SyntaxComparer.ComputeDistance(
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)),
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Token()
{
var distance = SyntaxComparer.ComputeDistance(SyntaxFactory.Literal("abc", "abc"), SyntaxFactory.Literal("acb", "acb"));
Assert.Equal(0.33, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Node()
{
var distance = SyntaxComparer.ComputeDistance(MakeLiteral(101), MakeLiteral(150));
Assert.Equal(1, Math.Round(distance, 2));
}
[Fact]
public void ComputeDistance_Null()
{
var distance = SyntaxComparer.ComputeDistance(
default,
ImmutableArray.Create(SyntaxFactory.Token(SyntaxKind.StaticKeyword)));
Assert.Equal(1, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
default,
ImmutableArray.Create(MakeLiteral(0)));
Assert.Equal(1, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
null,
Array.Empty<SyntaxNode>());
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
Array.Empty<SyntaxNode>(),
null);
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
null,
Array.Empty<SyntaxToken>());
Assert.Equal(0, Math.Round(distance, 2));
distance = SyntaxComparer.ComputeDistance(
Array.Empty<SyntaxToken>(),
null);
Assert.Equal(0, Math.Round(distance, 2));
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedSimpleConstructorSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represents a simple implementation of compiler generated constructors
''' </summary>
Friend Class SynthesizedSimpleConstructorSymbol
Inherits SynthesizedConstructorBase
Implements ISynthesizedMethodBodyImplementationSymbol
Private _parameters As ImmutableArray(Of ParameterSymbol)
Public Sub New(container As NamedTypeSymbol)
MyBase.New(VisualBasicSyntaxTree.DummyReference, container, False, Nothing, Nothing)
End Sub
' Note: This should be called at most once, immediately after the symbol is constructed. The parameters aren't
' Note: passed to the constructor because they need to have their container set correctly.
''' <summary>
''' Sets the parameters.
''' </summary>
''' <param name="parameters">The parameters.</param>
Friend Sub SetParameters(parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(Not parameters.IsDefault)
Debug.Assert(Me._parameters.IsDefault)
Me._parameters = parameters
End Sub
Friend NotOverridable Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return Me._parameters
End Get
End Property
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
Return False
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Dim symbol As ISynthesizedMethodBodyImplementationSymbol = CType(ContainingSymbol, ISynthesizedMethodBodyImplementationSymbol)
Return symbol.Method
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
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 Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represents a simple implementation of compiler generated constructors
''' </summary>
Friend Class SynthesizedSimpleConstructorSymbol
Inherits SynthesizedConstructorBase
Implements ISynthesizedMethodBodyImplementationSymbol
Private _parameters As ImmutableArray(Of ParameterSymbol)
Public Sub New(container As NamedTypeSymbol)
MyBase.New(VisualBasicSyntaxTree.DummyReference, container, False, Nothing, Nothing)
End Sub
' Note: This should be called at most once, immediately after the symbol is constructed. The parameters aren't
' Note: passed to the constructor because they need to have their container set correctly.
''' <summary>
''' Sets the parameters.
''' </summary>
''' <param name="parameters">The parameters.</param>
Friend Sub SetParameters(parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(Not parameters.IsDefault)
Debug.Assert(Me._parameters.IsDefault)
Me._parameters = parameters
End Sub
Friend NotOverridable Overrides ReadOnly Property ParameterCount As Integer
Get
Return Me._parameters.Length
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return Me._parameters
End Get
End Property
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
Return False
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Dim symbol As ISynthesizedMethodBodyImplementationSymbol = CType(ContainingSymbol, ISynthesizedMethodBodyImplementationSymbol)
Return symbol.Method
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService : IImplementInterfaceService
{
protected const string DisposingName = "disposing";
protected AbstractImplementInterfaceService()
{
}
protected abstract string ToDisplayString(IMethodSymbol disposeImplMethod, SymbolDisplayFormat format);
protected abstract bool CanImplementImplicitly { get; }
protected abstract bool HasHiddenExplicitImplementation { get; }
protected abstract bool TryInitializeState(Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken, out SyntaxNode classOrStructDecl, out INamedTypeSymbol classOrStructType, out IEnumerable<INamedTypeSymbol> interfaceTypes);
protected abstract SyntaxNode AddCommentInsideIfStatement(SyntaxNode ifDisposingStatement, SyntaxTriviaList trivia);
protected abstract SyntaxNode CreateFinalizer(SyntaxGenerator generator, INamedTypeSymbol classType, string disposeMethodDisplayString);
public async Task<Document> ImplementInterfaceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_ImplementInterface, cancellationToken))
{
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var state = State.Generate(this, document, model, node, cancellationToken);
if (state == null)
{
return document;
}
// While implementing just one default action, like in the case of pressing enter after interface name in VB,
// choose to implement with the dispose pattern as that's the Dev12 behavior.
var action = ShouldImplementDisposePattern(state, explicitly: false)
? ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state)
: ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
return await action.GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false);
}
}
public ImmutableArray<CodeAction> GetCodeActions(Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
{
var state = State.Generate(this, document, model, node, cancellationToken);
return GetActions(document, state).ToImmutableArray();
}
private IEnumerable<CodeAction> GetActions(Document document, State state)
{
if (state == null)
{
yield break;
}
if (state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length > 0)
{
yield return ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
if (ShouldImplementDisposePattern(state, explicitly: false))
{
yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state);
}
var delegatableMembers = GetDelegatableMembers(state);
foreach (var member in delegatableMembers)
{
yield return ImplementInterfaceCodeAction.CreateImplementThroughMemberCodeAction(this, document, state, member);
}
if (state.ClassOrStructType.IsAbstract)
{
yield return ImplementInterfaceCodeAction.CreateImplementAbstractlyCodeAction(this, document, state);
}
}
if (state.MembersWithoutExplicitImplementation.Length > 0)
{
yield return ImplementInterfaceCodeAction.CreateImplementExplicitlyCodeAction(this, document, state);
if (ShouldImplementDisposePattern(state, explicitly: true))
{
yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementExplicitlyWithDisposePatternCodeAction(this, document, state);
}
}
if (AnyImplementedImplicitly(state))
{
yield return ImplementInterfaceCodeAction.CreateImplementRemainingExplicitlyCodeAction(this, document, state);
}
}
private static bool AnyImplementedImplicitly(State state)
{
if (state.MembersWithoutExplicitOrImplicitImplementation.Length != state.MembersWithoutExplicitImplementation.Length)
{
return true;
}
for (var i = 0; i < state.MembersWithoutExplicitOrImplicitImplementation.Length; i++)
{
var (typeA, membersA) = state.MembersWithoutExplicitOrImplicitImplementation[i];
var (typeB, membersB) = state.MembersWithoutExplicitImplementation[i];
if (!typeA.Equals(typeB))
{
return true;
}
if (!membersA.SequenceEqual(membersB))
{
return true;
}
}
return false;
}
private static IList<ISymbol> GetDelegatableMembers(State state)
{
var fields =
state.ClassOrStructType.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => !f.IsImplicitlyDeclared)
.Where(f => f.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
.OfType<ISymbol>();
// Select all properties with zero parameters that also have a getter
var properties =
state.ClassOrStructType.GetMembers()
.OfType<IPropertySymbol>()
.Where(p => (!p.IsImplicitlyDeclared) && (p.Parameters.Length == 0) && (p.GetMethod != null))
.Where(p => p.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
.OfType<ISymbol>();
return fields.Concat(properties).ToList();
}
protected static TNode AddComment<TNode>(SyntaxGenerator g, string comment, TNode node) where TNode : SyntaxNode
=> AddComments(g, new[] { comment }, node);
protected static TNode AddComments<TNode>(SyntaxGenerator g, string comment1, string comment2, TNode node) where TNode : SyntaxNode
=> AddComments(g, new[] { comment1, comment2, }, node);
protected static TNode AddComments<TNode>(SyntaxGenerator g, string[] comments, TNode node) where TNode : SyntaxNode
=> node.WithPrependedLeadingTrivia(CreateCommentTrivia(g, comments));
protected static SyntaxTriviaList CreateCommentTrivia(SyntaxGenerator generator, params string[] comments)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var trivia);
foreach (var comment in comments)
{
trivia.Add(generator.SingleLineComment(" " + comment));
trivia.Add(generator.ElasticCarriageReturnLineFeed);
}
return new SyntaxTriviaList(trivia);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService : IImplementInterfaceService
{
protected const string DisposingName = "disposing";
protected AbstractImplementInterfaceService()
{
}
protected abstract string ToDisplayString(IMethodSymbol disposeImplMethod, SymbolDisplayFormat format);
protected abstract bool CanImplementImplicitly { get; }
protected abstract bool HasHiddenExplicitImplementation { get; }
protected abstract bool TryInitializeState(Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken, out SyntaxNode classOrStructDecl, out INamedTypeSymbol classOrStructType, out IEnumerable<INamedTypeSymbol> interfaceTypes);
protected abstract SyntaxNode AddCommentInsideIfStatement(SyntaxNode ifDisposingStatement, SyntaxTriviaList trivia);
protected abstract SyntaxNode CreateFinalizer(SyntaxGenerator generator, INamedTypeSymbol classType, string disposeMethodDisplayString);
public async Task<Document> ImplementInterfaceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_ImplementInterface, cancellationToken))
{
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var state = State.Generate(this, document, model, node, cancellationToken);
if (state == null)
{
return document;
}
// While implementing just one default action, like in the case of pressing enter after interface name in VB,
// choose to implement with the dispose pattern as that's the Dev12 behavior.
var action = ShouldImplementDisposePattern(state, explicitly: false)
? ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state)
: ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
return await action.GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false);
}
}
public ImmutableArray<CodeAction> GetCodeActions(Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken)
{
var state = State.Generate(this, document, model, node, cancellationToken);
return GetActions(document, state).ToImmutableArray();
}
private IEnumerable<CodeAction> GetActions(Document document, State state)
{
if (state == null)
{
yield break;
}
if (state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length > 0)
{
yield return ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
if (ShouldImplementDisposePattern(state, explicitly: false))
{
yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state);
}
var delegatableMembers = GetDelegatableMembers(state);
foreach (var member in delegatableMembers)
{
yield return ImplementInterfaceCodeAction.CreateImplementThroughMemberCodeAction(this, document, state, member);
}
if (state.ClassOrStructType.IsAbstract)
{
yield return ImplementInterfaceCodeAction.CreateImplementAbstractlyCodeAction(this, document, state);
}
}
if (state.MembersWithoutExplicitImplementation.Length > 0)
{
yield return ImplementInterfaceCodeAction.CreateImplementExplicitlyCodeAction(this, document, state);
if (ShouldImplementDisposePattern(state, explicitly: true))
{
yield return ImplementInterfaceWithDisposePatternCodeAction.CreateImplementExplicitlyWithDisposePatternCodeAction(this, document, state);
}
}
if (AnyImplementedImplicitly(state))
{
yield return ImplementInterfaceCodeAction.CreateImplementRemainingExplicitlyCodeAction(this, document, state);
}
}
private static bool AnyImplementedImplicitly(State state)
{
if (state.MembersWithoutExplicitOrImplicitImplementation.Length != state.MembersWithoutExplicitImplementation.Length)
{
return true;
}
for (var i = 0; i < state.MembersWithoutExplicitOrImplicitImplementation.Length; i++)
{
var (typeA, membersA) = state.MembersWithoutExplicitOrImplicitImplementation[i];
var (typeB, membersB) = state.MembersWithoutExplicitImplementation[i];
if (!typeA.Equals(typeB))
{
return true;
}
if (!membersA.SequenceEqual(membersB))
{
return true;
}
}
return false;
}
private static IList<ISymbol> GetDelegatableMembers(State state)
{
var fields =
state.ClassOrStructType.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => !f.IsImplicitlyDeclared)
.Where(f => f.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
.OfType<ISymbol>();
// Select all properties with zero parameters that also have a getter
var properties =
state.ClassOrStructType.GetMembers()
.OfType<IPropertySymbol>()
.Where(p => (!p.IsImplicitlyDeclared) && (p.Parameters.Length == 0) && (p.GetMethod != null))
.Where(p => p.Type.GetAllInterfacesIncludingThis().Contains(state.InterfaceTypes.First()))
.OfType<ISymbol>();
return fields.Concat(properties).ToList();
}
protected static TNode AddComment<TNode>(SyntaxGenerator g, string comment, TNode node) where TNode : SyntaxNode
=> AddComments(g, new[] { comment }, node);
protected static TNode AddComments<TNode>(SyntaxGenerator g, string comment1, string comment2, TNode node) where TNode : SyntaxNode
=> AddComments(g, new[] { comment1, comment2, }, node);
protected static TNode AddComments<TNode>(SyntaxGenerator g, string[] comments, TNode node) where TNode : SyntaxNode
=> node.WithPrependedLeadingTrivia(CreateCommentTrivia(g, comments));
protected static SyntaxTriviaList CreateCommentTrivia(SyntaxGenerator generator, params string[] comments)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var trivia);
foreach (var comment in comments)
{
trivia.Add(generator.SingleLineComment(" " + comment));
trivia.Add(generator.ElasticCarriageReturnLineFeed);
}
return new SyntaxTriviaList(trivia);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/Editing/ImportAdderService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
internal abstract class ImportAdderService : ILanguageService
{
public enum Strategy
{
AddImportsFromSyntaxes,
AddImportsFromSymbolAnnotations,
}
public async Task<Document> AddImportsAsync(
Document document,
IEnumerable<TextSpan> spans,
Strategy strategy,
OptionSet? options,
CancellationToken cancellationToken)
{
options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var addImportsService = document.GetRequiredLanguageService<IAddImportsService>();
var generator = document.GetRequiredLanguageService<SyntaxGenerator>();
// Create a simple interval tree for simplification spans.
var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans);
Func<SyntaxNode, bool> overlapsWithSpan = n => spansTree.HasIntervalThatOverlapsWith(n.FullSpan.Start, n.FullSpan.Length);
// Only dive deeper into nodes that actually overlap with the span we care about. And also only include
// those child nodes that themselves overlap with the span. i.e. if we have:
//
// Parent
// / \
// A [| B C |] D
//
// We'll dive under the parent because it overlaps with the span. But we only want to include (and dive
// into) B and C not A and D.
var nodes = root.DescendantNodesAndSelf(overlapsWithSpan).Where(overlapsWithSpan);
var allowInHiddenRegions = document.CanAddImportsInHiddenRegions();
if (strategy == Strategy.AddImportsFromSymbolAnnotations)
return await AddImportDirectivesFromSymbolAnnotationsAsync(document, options, nodes, addImportsService, generator, allowInHiddenRegions, cancellationToken).ConfigureAwait(false);
if (strategy == Strategy.AddImportsFromSyntaxes)
return await AddImportDirectivesFromSyntaxesAsync(document, options, nodes, addImportsService, generator, allowInHiddenRegions, cancellationToken).ConfigureAwait(false);
throw ExceptionUtilities.UnexpectedValue(strategy);
}
protected abstract INamespaceSymbol? GetExplicitNamespaceSymbol(SyntaxNode node, SemanticModel model);
private ISet<INamespaceSymbol> GetSafeToAddImports(
ImmutableArray<INamespaceSymbol> namespaceSymbols,
SyntaxNode container,
SemanticModel model,
CancellationToken cancellationToken)
{
using var _ = PooledHashSet<INamespaceSymbol>.GetInstance(out var conflicts);
AddPotentiallyConflictingImports(
model, container, namespaceSymbols, conflicts, cancellationToken);
return namespaceSymbols.Except(conflicts).ToSet();
}
/// <summary>
/// Looks at the contents of the document for top level identifiers (or existing extension method calls), and
/// blocks off imports that could potentially bring in a name that would conflict with them.
/// <paramref name="container"/> is the node that the import will be added to. This will either be the
/// compilation-unit node, or one of the namespace-blocks in the file.
/// </summary>
protected abstract void AddPotentiallyConflictingImports(
SemanticModel model,
SyntaxNode container,
ImmutableArray<INamespaceSymbol> namespaceSymbols,
HashSet<INamespaceSymbol> conflicts,
CancellationToken cancellationToken);
private static SyntaxNode GenerateNamespaceImportDeclaration(INamespaceSymbol namespaceSymbol, SyntaxGenerator generator)
{
// We add Simplifier.Annotation so that the import can be removed if it turns out to be unnecessary.
// This can happen for a number of reasons (we replace the type with var, inbuilt type, alias, etc.)
return generator
.NamespaceImportDeclaration(namespaceSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat))
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
}
private async Task<Document> AddImportDirectivesFromSyntaxesAsync(
Document document,
OptionSet options,
IEnumerable<SyntaxNode> syntaxNodes,
IAddImportsService addImportsService,
SyntaxGenerator generator,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var importsToAdd);
using var _2 = ArrayBuilder<SyntaxNode>.GetInstance(out var nodesToSimplify);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodesWithExplicitNamespaces = syntaxNodes
.Select(n => (syntaxnode: n, namespaceSymbol: GetExplicitNamespaceSymbol(n, model)))
.Where(x => x.namespaceSymbol != null);
var addedSymbols = new HashSet<INamespaceSymbol>();
foreach (var (node, namespaceSymbol) in nodesWithExplicitNamespaces)
{
cancellationToken.ThrowIfCancellationRequested();
nodesToSimplify.Add(node);
if (addedSymbols.Contains(namespaceSymbol))
continue;
var namespaceSyntax = GenerateNamespaceImportDeclaration(namespaceSymbol, generator);
if (addImportsService.HasExistingImport(model.Compilation, root, node, namespaceSyntax, generator))
continue;
if (IsInsideNamespace(node, namespaceSymbol, model, cancellationToken))
continue;
addedSymbols.Add(namespaceSymbol);
importsToAdd.Add(namespaceSyntax);
}
if (nodesToSimplify.Count == 0)
return document;
var annotation = new SyntaxAnnotation();
root = root.ReplaceNodes(
nodesToSimplify,
(o, r) => r.WithAdditionalAnnotations(Simplifier.Annotation, annotation));
var first = root.DescendantNodesAndSelf().First(x => x.HasAnnotation(annotation));
var last = root.DescendantNodesAndSelf().Last(x => x.HasAnnotation(annotation));
var context = first.GetCommonRoot(last);
root = addImportsService.AddImports(
model.Compilation, root, context, importsToAdd, generator, options,
allowInHiddenRegions, cancellationToken);
return document.WithSyntaxRoot(root);
}
private async Task<Document> AddImportDirectivesFromSymbolAnnotationsAsync(
Document document,
OptionSet options,
IEnumerable<SyntaxNode> syntaxNodes,
IAddImportsService addImportsService,
SyntaxGenerator generator,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
using var _ = PooledDictionary<INamespaceSymbol, SyntaxNode>.GetInstance(out var importToSyntax);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode? first = null, last = null;
var annotatedNodes = syntaxNodes.Where(x => x.HasAnnotations(SymbolAnnotation.Kind));
foreach (var annotatedNode in annotatedNodes)
{
cancellationToken.ThrowIfCancellationRequested();
if (annotatedNode.GetAnnotations(DoNotAddImportsAnnotation.Kind).Any())
continue;
var annotations = annotatedNode.GetAnnotations(SymbolAnnotation.Kind);
foreach (var annotation in annotations)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var namedType in SymbolAnnotation.GetSymbols(annotation, model.Compilation).OfType<INamedTypeSymbol>())
{
cancellationToken.ThrowIfCancellationRequested();
if (namedType.OriginalDefinition.IsSpecialType() || namedType.IsNullable() || namedType.IsTupleType)
continue;
var namespaceSymbol = namedType.ContainingNamespace;
if (namespaceSymbol is null || namespaceSymbol.IsGlobalNamespace)
continue;
first ??= annotatedNode;
last = annotatedNode;
if (importToSyntax.ContainsKey(namespaceSymbol))
continue;
var namespaceSyntax = GenerateNamespaceImportDeclaration(namespaceSymbol, generator);
if (addImportsService.HasExistingImport(model.Compilation, root, annotatedNode, namespaceSyntax, generator))
continue;
if (IsInsideNamespace(annotatedNode, namespaceSymbol, model, cancellationToken))
continue;
importToSyntax[namespaceSymbol] = namespaceSyntax;
}
}
}
if (first == null || last == null || importToSyntax.Count == 0)
return document;
var context = first.GetCommonRoot(last);
// Find the namespace/compilation-unit we'll be adding all these imports to.
var importContainer = addImportsService.GetImportContainer(root, context, importToSyntax.First().Value, options);
// Now remove any imports we think can cause conflicts in that container.
var safeImportsToAdd = GetSafeToAddImports(importToSyntax.Keys.ToImmutableArray(), importContainer, model, cancellationToken);
var importsToAdd = importToSyntax.Where(kvp => safeImportsToAdd.Contains(kvp.Key)).Select(kvp => kvp.Value).ToImmutableArray();
if (importsToAdd.Length == 0)
return document;
root = addImportsService.AddImports(
model.Compilation, root, context, importsToAdd, generator, options,
allowInHiddenRegions, cancellationToken);
return document.WithSyntaxRoot(root);
}
/// <summary>
/// Checks if the namespace declaration <paramref name="node"/> is contained inside,
/// or any of its ancestor namespaces are the same as <paramref name="symbol"/>
/// </summary>
private static bool IsInsideNamespace(SyntaxNode node, INamespaceSymbol symbol, SemanticModel model, CancellationToken cancellationToken)
{
var containedNamespace = model.GetEnclosingNamespace(node.SpanStart, cancellationToken);
while (containedNamespace != null)
{
if (containedNamespace.Equals(symbol))
return true;
containedNamespace = containedNamespace.ContainingNamespace;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editing
{
internal abstract class ImportAdderService : ILanguageService
{
public enum Strategy
{
AddImportsFromSyntaxes,
AddImportsFromSymbolAnnotations,
}
public async Task<Document> AddImportsAsync(
Document document,
IEnumerable<TextSpan> spans,
Strategy strategy,
OptionSet? options,
CancellationToken cancellationToken)
{
options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var addImportsService = document.GetRequiredLanguageService<IAddImportsService>();
var generator = document.GetRequiredLanguageService<SyntaxGenerator>();
// Create a simple interval tree for simplification spans.
var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans);
Func<SyntaxNode, bool> overlapsWithSpan = n => spansTree.HasIntervalThatOverlapsWith(n.FullSpan.Start, n.FullSpan.Length);
// Only dive deeper into nodes that actually overlap with the span we care about. And also only include
// those child nodes that themselves overlap with the span. i.e. if we have:
//
// Parent
// / \
// A [| B C |] D
//
// We'll dive under the parent because it overlaps with the span. But we only want to include (and dive
// into) B and C not A and D.
var nodes = root.DescendantNodesAndSelf(overlapsWithSpan).Where(overlapsWithSpan);
var allowInHiddenRegions = document.CanAddImportsInHiddenRegions();
if (strategy == Strategy.AddImportsFromSymbolAnnotations)
return await AddImportDirectivesFromSymbolAnnotationsAsync(document, options, nodes, addImportsService, generator, allowInHiddenRegions, cancellationToken).ConfigureAwait(false);
if (strategy == Strategy.AddImportsFromSyntaxes)
return await AddImportDirectivesFromSyntaxesAsync(document, options, nodes, addImportsService, generator, allowInHiddenRegions, cancellationToken).ConfigureAwait(false);
throw ExceptionUtilities.UnexpectedValue(strategy);
}
protected abstract INamespaceSymbol? GetExplicitNamespaceSymbol(SyntaxNode node, SemanticModel model);
private ISet<INamespaceSymbol> GetSafeToAddImports(
ImmutableArray<INamespaceSymbol> namespaceSymbols,
SyntaxNode container,
SemanticModel model,
CancellationToken cancellationToken)
{
using var _ = PooledHashSet<INamespaceSymbol>.GetInstance(out var conflicts);
AddPotentiallyConflictingImports(
model, container, namespaceSymbols, conflicts, cancellationToken);
return namespaceSymbols.Except(conflicts).ToSet();
}
/// <summary>
/// Looks at the contents of the document for top level identifiers (or existing extension method calls), and
/// blocks off imports that could potentially bring in a name that would conflict with them.
/// <paramref name="container"/> is the node that the import will be added to. This will either be the
/// compilation-unit node, or one of the namespace-blocks in the file.
/// </summary>
protected abstract void AddPotentiallyConflictingImports(
SemanticModel model,
SyntaxNode container,
ImmutableArray<INamespaceSymbol> namespaceSymbols,
HashSet<INamespaceSymbol> conflicts,
CancellationToken cancellationToken);
private static SyntaxNode GenerateNamespaceImportDeclaration(INamespaceSymbol namespaceSymbol, SyntaxGenerator generator)
{
// We add Simplifier.Annotation so that the import can be removed if it turns out to be unnecessary.
// This can happen for a number of reasons (we replace the type with var, inbuilt type, alias, etc.)
return generator
.NamespaceImportDeclaration(namespaceSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat))
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
}
private async Task<Document> AddImportDirectivesFromSyntaxesAsync(
Document document,
OptionSet options,
IEnumerable<SyntaxNode> syntaxNodes,
IAddImportsService addImportsService,
SyntaxGenerator generator,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var importsToAdd);
using var _2 = ArrayBuilder<SyntaxNode>.GetInstance(out var nodesToSimplify);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodesWithExplicitNamespaces = syntaxNodes
.Select(n => (syntaxnode: n, namespaceSymbol: GetExplicitNamespaceSymbol(n, model)))
.Where(x => x.namespaceSymbol != null);
var addedSymbols = new HashSet<INamespaceSymbol>();
foreach (var (node, namespaceSymbol) in nodesWithExplicitNamespaces)
{
cancellationToken.ThrowIfCancellationRequested();
nodesToSimplify.Add(node);
if (addedSymbols.Contains(namespaceSymbol))
continue;
var namespaceSyntax = GenerateNamespaceImportDeclaration(namespaceSymbol, generator);
if (addImportsService.HasExistingImport(model.Compilation, root, node, namespaceSyntax, generator))
continue;
if (IsInsideNamespace(node, namespaceSymbol, model, cancellationToken))
continue;
addedSymbols.Add(namespaceSymbol);
importsToAdd.Add(namespaceSyntax);
}
if (nodesToSimplify.Count == 0)
return document;
var annotation = new SyntaxAnnotation();
root = root.ReplaceNodes(
nodesToSimplify,
(o, r) => r.WithAdditionalAnnotations(Simplifier.Annotation, annotation));
var first = root.DescendantNodesAndSelf().First(x => x.HasAnnotation(annotation));
var last = root.DescendantNodesAndSelf().Last(x => x.HasAnnotation(annotation));
var context = first.GetCommonRoot(last);
root = addImportsService.AddImports(
model.Compilation, root, context, importsToAdd, generator, options,
allowInHiddenRegions, cancellationToken);
return document.WithSyntaxRoot(root);
}
private async Task<Document> AddImportDirectivesFromSymbolAnnotationsAsync(
Document document,
OptionSet options,
IEnumerable<SyntaxNode> syntaxNodes,
IAddImportsService addImportsService,
SyntaxGenerator generator,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
using var _ = PooledDictionary<INamespaceSymbol, SyntaxNode>.GetInstance(out var importToSyntax);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
SyntaxNode? first = null, last = null;
var annotatedNodes = syntaxNodes.Where(x => x.HasAnnotations(SymbolAnnotation.Kind));
foreach (var annotatedNode in annotatedNodes)
{
cancellationToken.ThrowIfCancellationRequested();
if (annotatedNode.GetAnnotations(DoNotAddImportsAnnotation.Kind).Any())
continue;
var annotations = annotatedNode.GetAnnotations(SymbolAnnotation.Kind);
foreach (var annotation in annotations)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var namedType in SymbolAnnotation.GetSymbols(annotation, model.Compilation).OfType<INamedTypeSymbol>())
{
cancellationToken.ThrowIfCancellationRequested();
if (namedType.OriginalDefinition.IsSpecialType() || namedType.IsNullable() || namedType.IsTupleType)
continue;
var namespaceSymbol = namedType.ContainingNamespace;
if (namespaceSymbol is null || namespaceSymbol.IsGlobalNamespace)
continue;
first ??= annotatedNode;
last = annotatedNode;
if (importToSyntax.ContainsKey(namespaceSymbol))
continue;
var namespaceSyntax = GenerateNamespaceImportDeclaration(namespaceSymbol, generator);
if (addImportsService.HasExistingImport(model.Compilation, root, annotatedNode, namespaceSyntax, generator))
continue;
if (IsInsideNamespace(annotatedNode, namespaceSymbol, model, cancellationToken))
continue;
importToSyntax[namespaceSymbol] = namespaceSyntax;
}
}
}
if (first == null || last == null || importToSyntax.Count == 0)
return document;
var context = first.GetCommonRoot(last);
// Find the namespace/compilation-unit we'll be adding all these imports to.
var importContainer = addImportsService.GetImportContainer(root, context, importToSyntax.First().Value, options);
// Now remove any imports we think can cause conflicts in that container.
var safeImportsToAdd = GetSafeToAddImports(importToSyntax.Keys.ToImmutableArray(), importContainer, model, cancellationToken);
var importsToAdd = importToSyntax.Where(kvp => safeImportsToAdd.Contains(kvp.Key)).Select(kvp => kvp.Value).ToImmutableArray();
if (importsToAdd.Length == 0)
return document;
root = addImportsService.AddImports(
model.Compilation, root, context, importsToAdd, generator, options,
allowInHiddenRegions, cancellationToken);
return document.WithSyntaxRoot(root);
}
/// <summary>
/// Checks if the namespace declaration <paramref name="node"/> is contained inside,
/// or any of its ancestor namespaces are the same as <paramref name="symbol"/>
/// </summary>
private static bool IsInsideNamespace(SyntaxNode node, INamespaceSymbol symbol, SemanticModel model, CancellationToken cancellationToken)
{
var containedNamespace = model.GetEnclosingNamespace(node.SpanStart, cancellationToken);
while (containedNamespace != null)
{
if (containedNamespace.Equals(symbol))
return true;
containedNamespace = containedNamespace.ContainingNamespace;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/Semantic/Extensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
' This is deliberately declared in the global namespace so that it will always be discoverable (regardless of Imports).
Friend Module Extensions
''' <summary>
''' This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation.
''' </summary>
''' <param name="node">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param>
<Extension()>
Friend Function GetDeclaredSymbolFromSyntaxNode(model As SemanticModel, node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As Symbol
If Not (
TypeOf node Is AggregationRangeVariableSyntax OrElse
TypeOf node Is AnonymousObjectCreationExpressionSyntax OrElse
TypeOf node Is SimpleImportsClauseSyntax OrElse
TypeOf node Is CatchStatementSyntax OrElse
TypeOf node Is CollectionRangeVariableSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is EnumStatementSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is ExpressionRangeVariableSyntax OrElse
TypeOf node Is ForEachStatementSyntax OrElse
TypeOf node Is FieldInitializerSyntax OrElse
TypeOf node Is ForStatementSyntax OrElse
TypeOf node Is LabelStatementSyntax OrElse
TypeOf node Is MethodBaseSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is ModifiedIdentifierSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is NamespaceStatementSyntax OrElse
TypeOf node Is ParameterSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is PropertyStatementSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is TypeParameterSyntax OrElse
TypeOf node Is TypeStatementSyntax) _
Then
Throw New NotSupportedException("This node type is not supported.")
End If
Return DirectCast(model.GetDeclaredSymbol(node, cancellationToken), Symbol)
End Function
End Module
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
' This is deliberately declared in the global namespace so that it will always be discoverable (regardless of Imports).
Friend Module Extensions
''' <summary>
''' This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation.
''' </summary>
''' <param name="node">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param>
<Extension()>
Friend Function GetDeclaredSymbolFromSyntaxNode(model As SemanticModel, node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As Symbol
If Not (
TypeOf node Is AggregationRangeVariableSyntax OrElse
TypeOf node Is AnonymousObjectCreationExpressionSyntax OrElse
TypeOf node Is SimpleImportsClauseSyntax OrElse
TypeOf node Is CatchStatementSyntax OrElse
TypeOf node Is CollectionRangeVariableSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is EnumStatementSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is ExpressionRangeVariableSyntax OrElse
TypeOf node Is ForEachStatementSyntax OrElse
TypeOf node Is FieldInitializerSyntax OrElse
TypeOf node Is ForStatementSyntax OrElse
TypeOf node Is LabelStatementSyntax OrElse
TypeOf node Is MethodBaseSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is ModifiedIdentifierSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is NamespaceStatementSyntax OrElse
TypeOf node Is ParameterSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is PropertyStatementSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is TypeParameterSyntax OrElse
TypeOf node Is TypeStatementSyntax) _
Then
Throw New NotSupportedException("This node type is not supported.")
End If
Return DirectCast(model.GetDeclaredSymbol(node, cancellationToken), Symbol)
End Function
End Module
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSingleLineIf.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.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenSingleLineIf
Inherits BasicTestBase
<Fact()>
Public Sub SingleLineIf()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
M(True, False)
M(False, True)
End Sub
Sub M(e1 As Boolean, e2 As Boolean)
Console.WriteLine("M({0}, {1})", e1, e2)
If e1 Then M(1) : M(2)
If e1 Then M(3) Else M(4)
If e1 Then M(5) : Else M(6)
If e1 Then Else M(7) : M(8)
If e1 Then Else : M(9)
If e1 Then If e2 Then Else M(10) Else M(11)
If e1 Then If e2 Then Else Else M(12)
If e1 Then Else If e2 Then Else M(13)
End Sub
Sub M(i As Integer)
Console.WriteLine("{0}", i)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
M(True, False)
1
2
3
5
9
10
M(False, True)
4
6
7
8
9
11
12
]]>)
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.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenSingleLineIf
Inherits BasicTestBase
<Fact()>
Public Sub SingleLineIf()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
M(True, False)
M(False, True)
End Sub
Sub M(e1 As Boolean, e2 As Boolean)
Console.WriteLine("M({0}, {1})", e1, e2)
If e1 Then M(1) : M(2)
If e1 Then M(3) Else M(4)
If e1 Then M(5) : Else M(6)
If e1 Then Else M(7) : M(8)
If e1 Then Else : M(9)
If e1 Then If e2 Then Else M(10) Else M(11)
If e1 Then If e2 Then Else Else M(12)
If e1 Then Else If e2 Then Else M(13)
End Sub
Sub M(i As Integer)
Console.WriteLine("{0}", i)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
M(True, False)
1
2
3
5
9
10
M(False, True)
4
6
7
8
9
11
12
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Extensions/ProjectItemExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using EnvDTE;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions
{
internal static class ProjectItemExtensions
{
public static ProjectItem FindItem(this ProjectItem item, string itemName, StringComparer comparer)
=> item.ProjectItems.FindItem(itemName, comparer);
public static bool TryGetFullPath(this ProjectItem item, [NotNullWhen(returnValue: true)] out string? fullPath)
{
fullPath = item.Properties.Item("FullPath").Value as string;
return fullPath != null;
}
public static bool IsFolder(this ProjectItem item)
=> item != null && item.Kind == Constants.vsProjectItemKindPhysicalFolder;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using EnvDTE;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions
{
internal static class ProjectItemExtensions
{
public static ProjectItem FindItem(this ProjectItem item, string itemName, StringComparer comparer)
=> item.ProjectItems.FindItem(itemName, comparer);
public static bool TryGetFullPath(this ProjectItem item, [NotNullWhen(returnValue: true)] out string? fullPath)
{
fullPath = item.Properties.Item("FullPath").Value as string;
return fullPath != null;
}
public static bool IsFolder(this ProjectItem item)
=> item != null && item.Kind == Constants.vsProjectItemKindPhysicalFolder;
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.FunctionResolution;
using Microsoft.VisualStudio.Debugger.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal abstract class FunctionResolver :
FunctionResolverBase<DkmProcess, DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest>,
IDkmRuntimeFunctionResolver,
IDkmModuleInstanceLoadNotification,
IDkmModuleInstanceUnloadNotification,
IDkmModuleModifiedNotification,
IDkmModuleSymbolsLoadedNotification
{
void IDkmRuntimeFunctionResolver.EnableResolution(DkmRuntimeFunctionResolutionRequest request, DkmWorkList workList)
{
if (request.LineOffset > 0)
{
return;
}
EnableResolution(request.Process, request, OnFunctionResolved(workList));
}
void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor)
{
OnModuleLoad(moduleInstance, workList);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
// Implementing IDkmModuleInstanceUnloadNotification
// (with Synchronized="true" in .vsdconfigxml) prevents
// caller from unloading modules while binding.
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
// Implementing IDkmModuleModifiedNotification
// (with Synchronized="true" in .vsdconfigxml) prevents
// caller from modifying modules while binding.
}
void IDkmModuleSymbolsLoadedNotification.OnModuleSymbolsLoaded(DkmModuleInstance moduleInstance, DkmModule module, bool isReload, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
OnModuleLoad(moduleInstance, workList);
}
private void OnModuleLoad(DkmModuleInstance moduleInstance, DkmWorkList workList)
{
var module = moduleInstance as DkmClrModuleInstance;
Debug.Assert(module != null); // <Filter><RuntimeId RequiredValue="DkmRuntimeId.Clr"/></Filter> should ensure this.
if (module == null)
{
// Only interested in managed modules.
return;
}
if (module.Module == null)
{
// Only resolve breakpoints if symbols have been loaded.
return;
}
OnModuleLoad(module.Process, module, OnFunctionResolved(workList));
}
internal sealed override bool ShouldEnableFunctionResolver(DkmProcess process)
{
var dataItem = process.GetDataItem<FunctionResolverDataItem>();
if (dataItem == null)
{
var enable = ShouldEnable(process);
dataItem = new FunctionResolverDataItem(enable);
process.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem);
}
return dataItem.Enabled;
}
internal sealed override IEnumerable<DkmClrModuleInstance> GetAllModules(DkmProcess process)
{
foreach (var runtimeInstance in process.GetRuntimeInstances())
{
var runtime = runtimeInstance as DkmClrRuntimeInstance;
if (runtime == null)
{
continue;
}
foreach (var moduleInstance in runtime.GetModuleInstances())
{
// Only interested in managed modules.
if (moduleInstance is DkmClrModuleInstance module)
{
yield return module;
}
}
}
}
internal sealed override string GetModuleName(DkmClrModuleInstance module)
{
return module.Name;
}
internal sealed override unsafe bool TryGetMetadata(DkmClrModuleInstance module, out byte* pointer, out int length)
{
try
{
pointer = (byte*)module.GetMetaDataBytesPtr(out var size);
length = (int)size;
return true;
}
catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))
{
pointer = null;
length = 0;
return false;
}
}
internal sealed override DkmRuntimeFunctionResolutionRequest[] GetRequests(DkmProcess process)
{
return process.GetRuntimeFunctionResolutionRequests();
}
internal sealed override string GetRequestModuleName(DkmRuntimeFunctionResolutionRequest request)
{
return request.ModuleName;
}
internal sealed override Guid GetLanguageId(DkmRuntimeFunctionResolutionRequest request)
{
return request.CompilerId.LanguageId;
}
private static OnFunctionResolvedDelegate<DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest> OnFunctionResolved(DkmWorkList workList)
{
return (DkmClrModuleInstance module,
DkmRuntimeFunctionResolutionRequest request,
int token,
int version,
int ilOffset) =>
{
var address = DkmClrInstructionAddress.Create(
module.RuntimeInstance,
module,
new DkmClrMethodId(Token: token, Version: (uint)version),
NativeOffset: uint.MaxValue,
ILOffset: (uint)ilOffset,
CPUInstruction: null);
// Use async overload of OnFunctionResolved to avoid deadlock.
request.OnFunctionResolved(workList, address, result => { });
};
}
private static readonly Guid s_messageSourceId = new Guid("ac353c9b-c599-427b-9424-cbe1ad19f81e");
private static bool ShouldEnable(DkmProcess process)
{
var message = DkmCustomMessage.Create(
process.Connection,
process,
s_messageSourceId,
MessageCode: 1, // Is legacy EE enabled?
Parameter1: null,
Parameter2: null);
try
{
var reply = message.SendLower();
var result = (int)reply.Parameter1;
// Possible values are 0 = false, 1 = true, 2 = not ready.
// At this point, we should only get 0 or 1, but to be
// safe, treat values other than 0 or 1 as false.
Debug.Assert(result == 0 || result == 1);
return result == 0;
}
catch (NotImplementedException)
{
return false;
}
}
private sealed class FunctionResolverDataItem : DkmDataItem
{
internal FunctionResolverDataItem(bool enabled)
{
Enabled = enabled;
}
internal readonly bool Enabled;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.FunctionResolution;
using Microsoft.VisualStudio.Debugger.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal abstract class FunctionResolver :
FunctionResolverBase<DkmProcess, DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest>,
IDkmRuntimeFunctionResolver,
IDkmModuleInstanceLoadNotification,
IDkmModuleInstanceUnloadNotification,
IDkmModuleModifiedNotification,
IDkmModuleSymbolsLoadedNotification
{
void IDkmRuntimeFunctionResolver.EnableResolution(DkmRuntimeFunctionResolutionRequest request, DkmWorkList workList)
{
if (request.LineOffset > 0)
{
return;
}
EnableResolution(request.Process, request, OnFunctionResolved(workList));
}
void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor)
{
OnModuleLoad(moduleInstance, workList);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
// Implementing IDkmModuleInstanceUnloadNotification
// (with Synchronized="true" in .vsdconfigxml) prevents
// caller from unloading modules while binding.
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
// Implementing IDkmModuleModifiedNotification
// (with Synchronized="true" in .vsdconfigxml) prevents
// caller from modifying modules while binding.
}
void IDkmModuleSymbolsLoadedNotification.OnModuleSymbolsLoaded(DkmModuleInstance moduleInstance, DkmModule module, bool isReload, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
OnModuleLoad(moduleInstance, workList);
}
private void OnModuleLoad(DkmModuleInstance moduleInstance, DkmWorkList workList)
{
var module = moduleInstance as DkmClrModuleInstance;
Debug.Assert(module != null); // <Filter><RuntimeId RequiredValue="DkmRuntimeId.Clr"/></Filter> should ensure this.
if (module == null)
{
// Only interested in managed modules.
return;
}
if (module.Module == null)
{
// Only resolve breakpoints if symbols have been loaded.
return;
}
OnModuleLoad(module.Process, module, OnFunctionResolved(workList));
}
internal sealed override bool ShouldEnableFunctionResolver(DkmProcess process)
{
var dataItem = process.GetDataItem<FunctionResolverDataItem>();
if (dataItem == null)
{
var enable = ShouldEnable(process);
dataItem = new FunctionResolverDataItem(enable);
process.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem);
}
return dataItem.Enabled;
}
internal sealed override IEnumerable<DkmClrModuleInstance> GetAllModules(DkmProcess process)
{
foreach (var runtimeInstance in process.GetRuntimeInstances())
{
var runtime = runtimeInstance as DkmClrRuntimeInstance;
if (runtime == null)
{
continue;
}
foreach (var moduleInstance in runtime.GetModuleInstances())
{
// Only interested in managed modules.
if (moduleInstance is DkmClrModuleInstance module)
{
yield return module;
}
}
}
}
internal sealed override string GetModuleName(DkmClrModuleInstance module)
{
return module.Name;
}
internal sealed override unsafe bool TryGetMetadata(DkmClrModuleInstance module, out byte* pointer, out int length)
{
try
{
pointer = (byte*)module.GetMetaDataBytesPtr(out var size);
length = (int)size;
return true;
}
catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e))
{
pointer = null;
length = 0;
return false;
}
}
internal sealed override DkmRuntimeFunctionResolutionRequest[] GetRequests(DkmProcess process)
{
return process.GetRuntimeFunctionResolutionRequests();
}
internal sealed override string GetRequestModuleName(DkmRuntimeFunctionResolutionRequest request)
{
return request.ModuleName;
}
internal sealed override Guid GetLanguageId(DkmRuntimeFunctionResolutionRequest request)
{
return request.CompilerId.LanguageId;
}
private static OnFunctionResolvedDelegate<DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest> OnFunctionResolved(DkmWorkList workList)
{
return (DkmClrModuleInstance module,
DkmRuntimeFunctionResolutionRequest request,
int token,
int version,
int ilOffset) =>
{
var address = DkmClrInstructionAddress.Create(
module.RuntimeInstance,
module,
new DkmClrMethodId(Token: token, Version: (uint)version),
NativeOffset: uint.MaxValue,
ILOffset: (uint)ilOffset,
CPUInstruction: null);
// Use async overload of OnFunctionResolved to avoid deadlock.
request.OnFunctionResolved(workList, address, result => { });
};
}
private static readonly Guid s_messageSourceId = new Guid("ac353c9b-c599-427b-9424-cbe1ad19f81e");
private static bool ShouldEnable(DkmProcess process)
{
var message = DkmCustomMessage.Create(
process.Connection,
process,
s_messageSourceId,
MessageCode: 1, // Is legacy EE enabled?
Parameter1: null,
Parameter2: null);
try
{
var reply = message.SendLower();
var result = (int)reply.Parameter1;
// Possible values are 0 = false, 1 = true, 2 = not ready.
// At this point, we should only get 0 or 1, but to be
// safe, treat values other than 0 or 1 as false.
Debug.Assert(result == 0 || result == 1);
return result == 0;
}
catch (NotImplementedException)
{
return false;
}
}
private sealed class FunctionResolverDataItem : DkmDataItem
{
internal FunctionResolverDataItem(bool enabled)
{
Enabled = enabled;
}
internal readonly bool Enabled;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/Syntax/Parsing/StatementAttributeParsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.StatementAttributes)]
public class StatementAttributeParsingTests : ParsingTests
{
public StatementAttributeParsingTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void AttributeOnBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]{}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnEmptyStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EmptyStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnLabeledStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]
bar:
Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LabeledStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IdentifierToken, "bar");
N(SyntaxKind.ColonToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (7,9): warning CS0164: This label has not been referenced
// bar:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "bar").WithLocation(7, 9));
}
[Fact]
public void AttributeOnGotoStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]
goto bar;
bar:
Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GotoStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.GotoKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "bar");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LabeledStatement);
{
N(SyntaxKind.IdentifierToken, "bar");
N(SyntaxKind.ColonToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnBreakStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
while (true)
{
[A]
break;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.BreakStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.BreakKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13));
}
[Fact]
public void AttributeOnContinueStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
while (true)
{
[A]
continue;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ContinueStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ContinueKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13));
}
[Fact]
public void AttributeOnReturn()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]return;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnThrow()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]throw;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ThrowStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ThrowKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]throw;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause
// [A]throw;
Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 12));
}
[Fact]
public void AttributeOnYieldReturn()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield return 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.YieldReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.YieldKeyword);
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type
// void Goo()
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnYieldBreak()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield return 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.YieldReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.YieldKeyword);
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type
// void Goo()
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnNakedYield()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "yield");
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]yield
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0103: The name 'yield' does not exist in the current context
// [A]yield
Diagnostic(ErrorCode.ERR_NameNotInContext, "yield").WithArguments("yield").WithLocation(6, 12),
// (6,17): error CS1002: ; expected
// [A]yield
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 17));
}
[Fact]
public void AttributeOnWhileStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]while (true);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.EmptyStatement);
{
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnDoStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]do { } while (true);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DoStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DoKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnForStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]for (;;) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnNormalForEachStatement()
{
var test = UsingTree(@"
class C
{
void Goo(string[] vals)
{
[A]foreach (var v in vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.IdentifierToken, "v");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnForEachVariableStatement()
{
var test = UsingTree(@"
class C
{
void Goo((int, string)[] vals)
{
[A]foreach (var (i, s) in vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnUsingStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnAwaitUsingStatement1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]await using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12),
// (6,12): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12));
}
[Fact]
public void AttributeOnAwaitUsingStatement2()
{
var test = UsingTree(@"
class C
{
async void Goo()
{
[A]await using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12));
}
[Fact]
public void AttributeOnFixedStatement()
{
var test = UsingTree(@"
class C
{
unsafe void Goo(int[] vals)
{
[A]fixed (int* p = vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FixedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.FixedKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PointerType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.AsteriskToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "p");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
}
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Goo(int[] vals)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo").WithLocation(4, 17),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]fixed (int* p = vals) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnCheckedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]checked { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CheckedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.CheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnCheckedBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
checked [A]{ }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CheckedStatement);
{
N(SyntaxKind.CheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,17): error CS7014: Attributes are not valid in this context.
// checked [A]{ }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17));
}
[Fact]
public void AttributeOnUncheckedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]unchecked { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UncheckedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UncheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnUnsafeStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]unsafe { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UnsafeStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]unsafe { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0227: Unsafe code may only appear if compiling with /unsafe
// [A]unsafe { }
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 12));
}
[Fact]
public void AttributeOnUnsafeBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
unsafe [A]{ }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.ArrayType);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.CloseBracketToken);
}
}
M(SyntaxKind.VariableDeclarator);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS0106: The modifier 'unsafe' is not valid for this item
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_BadMemberFlag, "unsafe").WithArguments("unsafe").WithLocation(6, 9),
// (6,16): error CS1031: Type expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(6, 16),
// (6,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[A]").WithLocation(6, 16),
// (6,17): error CS0103: The name 'A' does not exist in the current context
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(6, 17),
// (6,19): error CS1001: Identifier expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(6, 19),
// (6,19): error CS1002: ; expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 19));
}
[Fact]
public void AttributeOnLockStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]lock (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LockStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.LockKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnIfStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]if (true) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnSwitchStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]switch (0) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]switch (0) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,23): warning CS1522: Empty switch block
// [A]switch (0) { }
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(6, 23));
}
[Fact]
public void AttributeOnStatementInSwitchSection()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
default:
[A]return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchSection);
{
N(SyntaxKind.DefaultSwitchLabel);
{
N(SyntaxKind.DefaultKeyword);
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (9,17): error CS7014: Attributes are not valid in this context.
// [A]return;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(9, 17));
}
[Fact]
public void AttributeOnStatementAboveCase()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
[A]
case 0:
return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): warning CS1522: Empty switch block
// {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9),
// (7,10): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10),
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13),
// (8,16): error CS1525: Invalid expression term 'case'
// [A]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("case").WithLocation(8, 16),
// (8,16): error CS1002: ; expected
// [A]
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16),
// (8,16): error CS1513: } expected
// [A]
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 16),
// (9,19): error CS1002: ; expected
// case 0:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 19),
// (9,19): error CS1513: } expected
// case 0:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 19),
// (13,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1));
}
[Fact]
public void AttributeOnStatementAboveDefaultCase()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
[A]
default:
return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultLiteralExpression);
{
N(SyntaxKind.DefaultKeyword);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): warning CS1522: Empty switch block
// {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9),
// (7,10): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10),
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13),
// (9,13): error CS8716: There is no target type for the default literal.
// default:
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13),
// (9,20): error CS1002: ; expected
// default:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 20),
// (9,20): error CS1513: } expected
// default:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 20),
// (13,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1));
}
[Fact]
public void AttributeOnTryStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]try { } finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]try { } finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnTryBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try [A] { } finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,13): error CS7014: Attributes are not valid in this context.
// try [A] { } finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 13));
}
[Fact]
public void AttributeOnFinally()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } [A] finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.FinallyClause);
{
M(SyntaxKind.FinallyKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.TryKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,15): error CS1524: Expected catch or finally
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15),
// (6,17): error CS7014: Attributes are not valid in this context.
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17),
// (6,21): error CS1003: Syntax error, 'try' expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_SyntaxError, "finally").WithArguments("try", "finally").WithLocation(6, 21),
// (6,21): error CS1514: { expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_LbraceExpected, "finally").WithLocation(6, 21),
// (6,21): error CS1513: } expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_RbraceExpected, "finally").WithLocation(6, 21));
}
[Fact]
public void AttributeOnFinallyBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } finally [A] { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,25): error CS7014: Attributes are not valid in this context.
// try { } finally [A] { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 25));
}
[Fact]
public void AttributeOnCatch()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } [A] catch { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.FinallyClause);
{
M(SyntaxKind.FinallyKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.TryKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CatchClause);
{
N(SyntaxKind.CatchKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,15): error CS1524: Expected catch or finally
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15),
// (6,17): error CS7014: Attributes are not valid in this context.
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17),
// (6,21): error CS1003: Syntax error, 'try' expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_SyntaxError, "catch").WithArguments("try", "catch").WithLocation(6, 21),
// (6,21): error CS1514: { expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_LbraceExpected, "catch").WithLocation(6, 21),
// (6,21): error CS1513: } expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_RbraceExpected, "catch").WithLocation(6, 21));
}
[Fact]
public void AttributeOnCatchBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } catch [A] { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CatchClause);
{
N(SyntaxKind.CatchKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,23): error CS7014: Attributes are not valid in this context.
// try { } catch [A] { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 23));
}
[Fact]
public void AttributeOnEmbeddedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
if (true) [A]return;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,19): error CS7014: Attributes are not valid in this context.
// if (true) [A]return;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 19));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_NoParameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,24): error CS1002: ; expected
// [A]delegate { }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 24));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_NoBody()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,20): error CS1514: { expected
// [A]delegate
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// [A]delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_Parameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate () { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate () { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]delegate () { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "delegate () { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_NoParameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]() => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]() => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]() => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "() => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_Parameters1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A](int i) => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](int i) => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](int i) => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int i) => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_Parameters2()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]i => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]i => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "i => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousObject()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ArrayCreation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new int[] { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new int[] { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new int[] { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new int[] { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousArrayCreation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new [] { 0 };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new [] { 0 };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new [] { 0 };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new [] { 0 }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Assignment()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_CompoundAssignment()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a += 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AddAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusEqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a += 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_AwaitExpression_NonAsyncContext()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]await a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0246: The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?)
// [A]await a;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "await").WithArguments("await").WithLocation(6, 12),
// (6,18): warning CS0168: The variable 'a' is declared but never used
// [A]await a;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 18));
}
[Fact]
public void AttributeOnExpressionStatement_AwaitExpression_AsyncContext()
{
var test = UsingTree(@"
class C
{
async void Goo()
{
[A]await a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitExpression);
{
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,18): error CS0103: The name 'a' does not exist in the current context
// [A]await a;
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 18));
}
[Fact]
public void AttributeOnExpressionStatement_BinaryExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a + a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a + a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a + a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a + a").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_CastExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A](object)a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.CastExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](object)a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](object)a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(object)a").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ConditionalAccess()
{
var test = UsingTree(@"
class C
{
void Goo(string a)
{
[A]a?.ToString();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConditionalAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.MemberBindingExpression);
{
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a?.ToString();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_DefaultExpression()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]default(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultExpression);
{
N(SyntaxKind.DefaultKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]default(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]default(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "default(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_DefaultLiteral()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]default;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultLiteralExpression);
{
N(SyntaxKind.DefaultKeyword);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]default;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS8716: There is no target type for the default literal.
// [A]default;
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]default;
Diagnostic(ErrorCode.ERR_IllegalStatement, "default").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ElementAccess()
{
var test = UsingTree(@"
class C
{
void Goo(string s)
{
[A]s[0];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]s[0];
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]s[0];
Diagnostic(ErrorCode.ERR_IllegalStatement, "s[0]").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ElementBinding()
{
var test = UsingTree(@"
class C
{
void Goo(string s)
{
[A]s?[0];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConditionalAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.ElementBindingExpression);
{
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]s?[0];
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]s?[0];
Diagnostic(ErrorCode.ERR_IllegalStatement, "s?[0]").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Invocation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]Goo();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Literal()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]0;
Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_MemberAccess()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]i.ToString;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i.ToString;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]i.ToString;
Diagnostic(ErrorCode.ERR_IllegalStatement, "i.ToString").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ObjectCreation_Builtin()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new int();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new int();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_ObjectCreation_TypeName()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new System.Int32();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Int32");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new System.Int32();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Parenthesized()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A](1);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](1);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](1);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(1)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_PostfixUnary()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]i++;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PostIncrementExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.PlusPlusToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i++;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_PrefixUnary()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]++i;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PreIncrementExpression);
{
N(SyntaxKind.PlusPlusToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]++i;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Query()
{
var test = UsingTree(@"
using System.Linq;
class C
{
void Goo(string s)
{
[A]from c in s select c;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.UsingDirective);
{
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Linq");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.QueryExpression);
{
N(SyntaxKind.FromClause);
{
N(SyntaxKind.FromKeyword);
N(SyntaxKind.IdentifierToken, "c");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
}
N(SyntaxKind.QueryBody);
{
N(SyntaxKind.SelectClause);
{
N(SyntaxKind.SelectKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): error CS7014: Attributes are not valid in this context.
// [A]from c in s select c;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(7, 9),
// (7,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]from c in s select c;
Diagnostic(ErrorCode.ERR_IllegalStatement, "from c in s select c").WithLocation(7, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Range1()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]a..b;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a..b;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..b").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a..b;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a..b").WithLocation(6, 12),
// (6,15): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 15));
}
[Fact]
public void AttributeOnExpressionStatement_Range2()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]a..;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a..;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]a..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a..;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a..").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Range3()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]..b;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]..b;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..b").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]..b;
Diagnostic(ErrorCode.ERR_IllegalStatement, "..b").WithLocation(6, 12),
// (6,14): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 14));
}
[Fact]
public void AttributeOnExpressionStatement_Range4()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]..;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]..;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]..;
Diagnostic(ErrorCode.ERR_IllegalStatement, "..").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Sizeof()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]sizeof(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SizeOfExpression);
{
N(SyntaxKind.SizeOfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]sizeof(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]sizeof(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "sizeof(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_SwitchExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a switch { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SwitchExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a switch { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a switch { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "a switch { }").WithLocation(6, 12),
// (6,14): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// [A]a switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 14),
// (6,14): error CS8506: No best type was found for the switch expression.
// [A]a switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 14));
}
[Fact]
public void AttributeOnExpressionStatement_TypeOf()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]typeof(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.TypeOfExpression);
{
N(SyntaxKind.TypeOfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]typeof(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]typeof(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "typeof(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnLocalDeclOrMember1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0168: The variable 'i' is declared but never used
// [A]int i;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16));
}
[Fact]
public void AttributeOnLocalDeclOrMember2()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i, j;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i, j;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0168: The variable 'i' is declared but never used
// [A]int i, j;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16),
// (6,19): warning CS0168: The variable 'j' is declared but never used
// [A]int i, j;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 19));
}
[Fact]
public void AttributeOnLocalDeclOrMember3()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 16));
}
[Fact]
public void AttributeOnLocalDeclOrMember4()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int this[int i] => 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
M(SyntaxKind.VariableDeclarator);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.ThisExpression);
{
N(SyntaxKind.ThisKeyword);
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): error CS1001: Identifier expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "this").WithLocation(6, 16),
// (6,16): error CS1002: ; expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "this").WithLocation(6, 16),
// (6,21): error CS1525: Invalid expression term 'int'
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21),
// (6,25): error CS1003: Syntax error, ',' expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SyntaxError, "i").WithArguments(",", "").WithLocation(6, 25),
// (6,25): error CS0103: The name 'i' does not exist in the current context
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25),
// (6,28): error CS1002: ; expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>").WithLocation(6, 28),
// (6,28): error CS1513: } expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 28),
// (6,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 31));
}
[Fact]
public void AttributeOnLocalDeclOrMember5()
{
var tree = UsingTree(@"
class C
{
void Goo()
{
[A]const int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConstKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(tree).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]const int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,22): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]const int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 22));
}
[Fact]
public void AccessModOnLocalDeclOrMember_01()
{
var test = UsingTree(@"
class C
{
void Goo()
{
public extern int i = 1;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.ExternKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).VerifyDiagnostics(
// (5,6): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 6),
// (6,27): error CS0106: The modifier 'extern' is not valid for this item
// public extern int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "i").WithArguments("extern").WithLocation(6, 27),
// (8,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(8, 1));
}
[Fact]
public void AccessModOnLocalDeclOrMember_02()
{
var test = UsingTree(@"
class C
{
void Goo()
{
extern public int i = 1;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.ExternKeyword);
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).VerifyDiagnostics(
// (6,9): error CS0106: The modifier 'extern' is not valid for this item
// extern public int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "extern").WithArguments("extern").WithLocation(6, 9),
// (6,16): error CS0106: The modifier 'public' is not valid for this item
// extern public int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 16),
// (6,27): warning CS0219: The variable 'i' is assigned but its value is never used
// extern public int i = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 27));
}
[Fact]
public void AttributeOnLocalDeclOrMember6()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]public int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]public int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0106: The modifier 'public' is not valid for this item
// [A]public int i = 0;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 12),
// (6,23): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]public int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 23));
}
[Fact]
public void AttributeOnLocalDeclOrMember7()
{
var test = UsingTree(@"
class C
{
void Goo(System.IDisposable d)
{
[A]using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnLocalDeclOrMember8()
{
var test = UsingTree(@"
class C
{
void Goo(System.IAsyncDisposable d)
{
[A]await using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IAsyncDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,21): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?)
// void Goo(System.IAsyncDisposable d)
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 21),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12));
}
[Fact]
public void AttributeOnLocalDeclOrMember9()
{
var test = UsingTree(@"
class C
{
async void Goo(System.IAsyncDisposable d)
{
[A]await using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IAsyncDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,27): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?)
// async void Goo(System.IAsyncDisposable d)
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 27),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12));
}
[Fact]
public void AttrDeclOnStatementWhereMemberExpected()
{
UsingTree(@"
class C
{
[Attr] x.y();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Attr");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.TupleElement);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CommaToken);
M(SyntaxKind.TupleElement);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.StatementAttributes)]
public class StatementAttributeParsingTests : ParsingTests
{
public StatementAttributeParsingTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void AttributeOnBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]{}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnEmptyStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EmptyStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnLabeledStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]
bar:
Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LabeledStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IdentifierToken, "bar");
N(SyntaxKind.ColonToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (7,9): warning CS0164: This label has not been referenced
// bar:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "bar").WithLocation(7, 9));
}
[Fact]
public void AttributeOnGotoStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]
goto bar;
bar:
Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GotoStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.GotoKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "bar");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LabeledStatement);
{
N(SyntaxKind.IdentifierToken, "bar");
N(SyntaxKind.ColonToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnBreakStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
while (true)
{
[A]
break;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.BreakStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.BreakKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13));
}
[Fact]
public void AttributeOnContinueStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
while (true)
{
[A]
continue;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ContinueStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ContinueKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13));
}
[Fact]
public void AttributeOnReturn()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]return;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnThrow()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]throw;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ThrowStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ThrowKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]throw;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause
// [A]throw;
Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 12));
}
[Fact]
public void AttributeOnYieldReturn()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield return 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.YieldReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.YieldKeyword);
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type
// void Goo()
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnYieldBreak()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield return 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.YieldReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.YieldKeyword);
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type
// void Goo()
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnNakedYield()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]yield
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "yield");
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]yield
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0103: The name 'yield' does not exist in the current context
// [A]yield
Diagnostic(ErrorCode.ERR_NameNotInContext, "yield").WithArguments("yield").WithLocation(6, 12),
// (6,17): error CS1002: ; expected
// [A]yield
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 17));
}
[Fact]
public void AttributeOnWhileStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]while (true);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.WhileStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.EmptyStatement);
{
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnDoStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]do { } while (true);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DoStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DoKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.WhileKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnForStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]for (;;) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnNormalForEachStatement()
{
var test = UsingTree(@"
class C
{
void Goo(string[] vals)
{
[A]foreach (var v in vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.IdentifierToken, "v");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnForEachVariableStatement()
{
var test = UsingTree(@"
class C
{
void Goo((int, string)[] vals)
{
[A]foreach (var (i, s) in vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnUsingStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnAwaitUsingStatement1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]await using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12),
// (6,12): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12));
}
[Fact]
public void AttributeOnAwaitUsingStatement2()
{
var test = UsingTree(@"
class C
{
async void Goo()
{
[A]await using (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UsingStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// [A]await using (null) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12));
}
[Fact]
public void AttributeOnFixedStatement()
{
var test = UsingTree(@"
class C
{
unsafe void Goo(int[] vals)
{
[A]fixed (int* p = vals) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.IdentifierToken, "vals");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FixedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.FixedKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PointerType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.AsteriskToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "p");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "vals");
}
}
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Goo(int[] vals)
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo").WithLocation(4, 17),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]fixed (int* p = vals) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnCheckedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]checked { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CheckedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.CheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnCheckedBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
checked [A]{ }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CheckedStatement);
{
N(SyntaxKind.CheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,17): error CS7014: Attributes are not valid in this context.
// checked [A]{ }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17));
}
[Fact]
public void AttributeOnUncheckedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]unchecked { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UncheckedStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UncheckedKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnUnsafeStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]unsafe { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.UnsafeStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]unsafe { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0227: Unsafe code may only appear if compiling with /unsafe
// [A]unsafe { }
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 12));
}
[Fact]
public void AttributeOnUnsafeBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
unsafe [A]{ }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.UnsafeKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.ArrayType);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.CloseBracketToken);
}
}
M(SyntaxKind.VariableDeclarator);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS0106: The modifier 'unsafe' is not valid for this item
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_BadMemberFlag, "unsafe").WithArguments("unsafe").WithLocation(6, 9),
// (6,16): error CS1031: Type expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(6, 16),
// (6,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[A]").WithLocation(6, 16),
// (6,17): error CS0103: The name 'A' does not exist in the current context
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(6, 17),
// (6,19): error CS1001: Identifier expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(6, 19),
// (6,19): error CS1002: ; expected
// unsafe [A]{ }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 19));
}
[Fact]
public void AttributeOnLockStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]lock (null) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LockStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.LockKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnIfStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]if (true) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnSwitchStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]switch (0) { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]switch (0) { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,23): warning CS1522: Empty switch block
// [A]switch (0) { }
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(6, 23));
}
[Fact]
public void AttributeOnStatementInSwitchSection()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
default:
[A]return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchSection);
{
N(SyntaxKind.DefaultSwitchLabel);
{
N(SyntaxKind.DefaultKeyword);
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (9,17): error CS7014: Attributes are not valid in this context.
// [A]return;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(9, 17));
}
[Fact]
public void AttributeOnStatementAboveCase()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
[A]
case 0:
return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): warning CS1522: Empty switch block
// {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9),
// (7,10): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10),
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13),
// (8,16): error CS1525: Invalid expression term 'case'
// [A]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("case").WithLocation(8, 16),
// (8,16): error CS1002: ; expected
// [A]
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16),
// (8,16): error CS1513: } expected
// [A]
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 16),
// (9,19): error CS1002: ; expected
// case 0:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 19),
// (9,19): error CS1513: } expected
// case 0:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 19),
// (13,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1));
}
[Fact]
public void AttributeOnStatementAboveDefaultCase()
{
var test = UsingTree(@"
class C
{
void Goo()
{
switch (0)
{
[A]
default:
return;
}
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultLiteralExpression);
{
N(SyntaxKind.DefaultKeyword);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): warning CS1522: Empty switch block
// {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9),
// (7,10): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10),
// (8,13): error CS7014: Attributes are not valid in this context.
// [A]
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13),
// (9,13): error CS8716: There is no target type for the default literal.
// default:
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13),
// (9,20): error CS1002: ; expected
// default:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 20),
// (9,20): error CS1513: } expected
// default:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 20),
// (13,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1));
}
[Fact]
public void AttributeOnTryStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]try { } finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]try { } finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnTryBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try [A] { } finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,13): error CS7014: Attributes are not valid in this context.
// try [A] { } finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 13));
}
[Fact]
public void AttributeOnFinally()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } [A] finally { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.FinallyClause);
{
M(SyntaxKind.FinallyKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.TryKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,15): error CS1524: Expected catch or finally
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15),
// (6,17): error CS7014: Attributes are not valid in this context.
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17),
// (6,21): error CS1003: Syntax error, 'try' expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_SyntaxError, "finally").WithArguments("try", "finally").WithLocation(6, 21),
// (6,21): error CS1514: { expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_LbraceExpected, "finally").WithLocation(6, 21),
// (6,21): error CS1513: } expected
// try { } [A] finally { }
Diagnostic(ErrorCode.ERR_RbraceExpected, "finally").WithLocation(6, 21));
}
[Fact]
public void AttributeOnFinallyBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } finally [A] { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.FinallyClause);
{
N(SyntaxKind.FinallyKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,25): error CS7014: Attributes are not valid in this context.
// try { } finally [A] { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 25));
}
[Fact]
public void AttributeOnCatch()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } [A] catch { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.FinallyClause);
{
M(SyntaxKind.FinallyKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.TryKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CatchClause);
{
N(SyntaxKind.CatchKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,15): error CS1524: Expected catch or finally
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15),
// (6,17): error CS7014: Attributes are not valid in this context.
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17),
// (6,21): error CS1003: Syntax error, 'try' expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_SyntaxError, "catch").WithArguments("try", "catch").WithLocation(6, 21),
// (6,21): error CS1514: { expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_LbraceExpected, "catch").WithLocation(6, 21),
// (6,21): error CS1513: } expected
// try { } [A] catch { }
Diagnostic(ErrorCode.ERR_RbraceExpected, "catch").WithLocation(6, 21));
}
[Fact]
public void AttributeOnCatchBlock()
{
var test = UsingTree(@"
class C
{
void Goo()
{
try { } catch [A] { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.TryStatement);
{
N(SyntaxKind.TryKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CatchClause);
{
N(SyntaxKind.CatchKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,23): error CS7014: Attributes are not valid in this context.
// try { } catch [A] { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 23));
}
[Fact]
public void AttributeOnEmbeddedStatement()
{
var test = UsingTree(@"
class C
{
void Goo()
{
if (true) [A]return;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,19): error CS7014: Attributes are not valid in this context.
// if (true) [A]return;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 19));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_NoParameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate { }
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate { }
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,24): error CS1002: ; expected
// [A]delegate { }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 24));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_NoBody()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
M(SyntaxKind.Block);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,20): error CS1514: { expected
// [A]delegate
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(6, 20),
// (6,20): error CS1002: ; expected
// [A]delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousMethod_Parameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]delegate () { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]delegate () { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]delegate () { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "delegate () { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_NoParameters()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]() => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]() => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]() => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "() => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_Parameters1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A](int i) => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](int i) => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](int i) => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int i) => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Lambda_Parameters2()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]i => { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i => { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]i => { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "i => { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousObject()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AnonymousObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ArrayCreation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new int[] { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new int[] { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new int[] { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new int[] { }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_AnonymousArrayCreation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new [] { 0 };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new [] { 0 };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]new [] { 0 };
Diagnostic(ErrorCode.ERR_IllegalStatement, "new [] { 0 }").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Assignment()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_CompoundAssignment()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a += 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AddAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusEqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a += 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_AwaitExpression_NonAsyncContext()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]await a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0246: The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?)
// [A]await a;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "await").WithArguments("await").WithLocation(6, 12),
// (6,18): warning CS0168: The variable 'a' is declared but never used
// [A]await a;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 18));
}
[Fact]
public void AttributeOnExpressionStatement_AwaitExpression_AsyncContext()
{
var test = UsingTree(@"
class C
{
async void Goo()
{
[A]await a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitExpression);
{
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,18): error CS0103: The name 'a' does not exist in the current context
// [A]await a;
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 18));
}
[Fact]
public void AttributeOnExpressionStatement_BinaryExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a + a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a + a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a + a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a + a").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_CastExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A](object)a;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.CastExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](object)a;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](object)a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(object)a").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ConditionalAccess()
{
var test = UsingTree(@"
class C
{
void Goo(string a)
{
[A]a?.ToString();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConditionalAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.MemberBindingExpression);
{
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a?.ToString();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_DefaultExpression()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]default(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultExpression);
{
N(SyntaxKind.DefaultKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]default(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]default(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "default(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_DefaultLiteral()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]default;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.DefaultLiteralExpression);
{
N(SyntaxKind.DefaultKeyword);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]default;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS8716: There is no target type for the default literal.
// [A]default;
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]default;
Diagnostic(ErrorCode.ERR_IllegalStatement, "default").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ElementAccess()
{
var test = UsingTree(@"
class C
{
void Goo(string s)
{
[A]s[0];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]s[0];
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]s[0];
Diagnostic(ErrorCode.ERR_IllegalStatement, "s[0]").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ElementBinding()
{
var test = UsingTree(@"
class C
{
void Goo(string s)
{
[A]s?[0];
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConditionalAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.ElementBindingExpression);
{
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]s?[0];
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]s?[0];
Diagnostic(ErrorCode.ERR_IllegalStatement, "s?[0]").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Invocation()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]Goo();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Goo");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]Goo();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Literal()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]0;
Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_MemberAccess()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]i.ToString;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i.ToString;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]i.ToString;
Diagnostic(ErrorCode.ERR_IllegalStatement, "i.ToString").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_ObjectCreation_Builtin()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new int();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new int();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_ObjectCreation_TypeName()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]new System.Int32();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Int32");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]new System.Int32();
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Parenthesized()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A](1);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A](1);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A](1);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(1)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_PostfixUnary()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]i++;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PostIncrementExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.PlusPlusToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]i++;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_PrefixUnary()
{
var test = UsingTree(@"
class C
{
void Goo(int i)
{
[A]++i;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PreIncrementExpression);
{
N(SyntaxKind.PlusPlusToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]++i;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnExpressionStatement_Query()
{
var test = UsingTree(@"
using System.Linq;
class C
{
void Goo(string s)
{
[A]from c in s select c;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.UsingDirective);
{
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Linq");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken, "s");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.QueryExpression);
{
N(SyntaxKind.FromClause);
{
N(SyntaxKind.FromKeyword);
N(SyntaxKind.IdentifierToken, "c");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "s");
}
}
N(SyntaxKind.QueryBody);
{
N(SyntaxKind.SelectClause);
{
N(SyntaxKind.SelectKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (7,9): error CS7014: Attributes are not valid in this context.
// [A]from c in s select c;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(7, 9),
// (7,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]from c in s select c;
Diagnostic(ErrorCode.ERR_IllegalStatement, "from c in s select c").WithLocation(7, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Range1()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]a..b;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a..b;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..b").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a..b;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a..b").WithLocation(6, 12),
// (6,15): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 15));
}
[Fact]
public void AttributeOnExpressionStatement_Range2()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]a..;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a..;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]a..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]a..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a..;
Diagnostic(ErrorCode.ERR_IllegalStatement, "a..").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Range3()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]..b;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]..b;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..b").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]..b;
Diagnostic(ErrorCode.ERR_IllegalStatement, "..b").WithLocation(6, 12),
// (6,14): error CS0518: Predefined type 'System.Index' is not defined or imported
// [A]..b;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 14));
}
[Fact]
public void AttributeOnExpressionStatement_Range4()
{
var test = UsingTree(@"
class C
{
void Goo(int a, int b)
{
[A]..;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]..;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported
// [A]..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(6, 12),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]..;
Diagnostic(ErrorCode.ERR_IllegalStatement, "..").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_Sizeof()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]sizeof(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SizeOfExpression);
{
N(SyntaxKind.SizeOfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]sizeof(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]sizeof(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "sizeof(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnExpressionStatement_SwitchExpression()
{
var test = UsingTree(@"
class C
{
void Goo(int a)
{
[A]a switch { };
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.SwitchExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]a switch { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]a switch { };
Diagnostic(ErrorCode.ERR_IllegalStatement, "a switch { }").WithLocation(6, 12),
// (6,14): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// [A]a switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 14),
// (6,14): error CS8506: No best type was found for the switch expression.
// [A]a switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 14));
}
[Fact]
public void AttributeOnExpressionStatement_TypeOf()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]typeof(int);
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.TypeOfExpression);
{
N(SyntaxKind.TypeOfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]typeof(int);
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]typeof(int);
Diagnostic(ErrorCode.ERR_IllegalStatement, "typeof(int)").WithLocation(6, 12));
}
[Fact]
public void AttributeOnLocalDeclOrMember1()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0168: The variable 'i' is declared but never used
// [A]int i;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16));
}
[Fact]
public void AttributeOnLocalDeclOrMember2()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i, j;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i, j;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0168: The variable 'i' is declared but never used
// [A]int i, j;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16),
// (6,19): warning CS0168: The variable 'j' is declared but never used
// [A]int i, j;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 19));
}
[Fact]
public void AttributeOnLocalDeclOrMember3()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 16));
}
[Fact]
public void AttributeOnLocalDeclOrMember4()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]int this[int i] => 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
M(SyntaxKind.VariableDeclarator);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.ThisExpression);
{
N(SyntaxKind.ThisKeyword);
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,16): error CS1001: Identifier expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "this").WithLocation(6, 16),
// (6,16): error CS1002: ; expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "this").WithLocation(6, 16),
// (6,21): error CS1525: Invalid expression term 'int'
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21),
// (6,25): error CS1003: Syntax error, ',' expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SyntaxError, "i").WithArguments(",", "").WithLocation(6, 25),
// (6,25): error CS0103: The name 'i' does not exist in the current context
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25),
// (6,28): error CS1002: ; expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>").WithLocation(6, 28),
// (6,28): error CS1513: } expected
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 28),
// (6,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// [A]int this[int i] => 0;
Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 31));
}
[Fact]
public void AttributeOnLocalDeclOrMember5()
{
var tree = UsingTree(@"
class C
{
void Goo()
{
[A]const int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ConstKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(tree).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]const int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,22): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]const int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 22));
}
[Fact]
public void AccessModOnLocalDeclOrMember_01()
{
var test = UsingTree(@"
class C
{
void Goo()
{
public extern int i = 1;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.ExternKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).VerifyDiagnostics(
// (5,6): error CS1513: } expected
// {
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 6),
// (6,27): error CS0106: The modifier 'extern' is not valid for this item
// public extern int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "i").WithArguments("extern").WithLocation(6, 27),
// (8,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(8, 1));
}
[Fact]
public void AccessModOnLocalDeclOrMember_02()
{
var test = UsingTree(@"
class C
{
void Goo()
{
extern public int i = 1;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.ExternKeyword);
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).VerifyDiagnostics(
// (6,9): error CS0106: The modifier 'extern' is not valid for this item
// extern public int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "extern").WithArguments("extern").WithLocation(6, 9),
// (6,16): error CS0106: The modifier 'public' is not valid for this item
// extern public int i = 1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 16),
// (6,27): warning CS0219: The variable 'i' is assigned but its value is never used
// extern public int i = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 27));
}
[Fact]
public void AttributeOnLocalDeclOrMember6()
{
var test = UsingTree(@"
class C
{
void Goo()
{
[A]public int i = 0;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]public int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0106: The modifier 'public' is not valid for this item
// [A]public int i = 0;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 12),
// (6,23): warning CS0219: The variable 'i' is assigned but its value is never used
// [A]public int i = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 23));
}
[Fact]
public void AttributeOnLocalDeclOrMember7()
{
var test = UsingTree(@"
class C
{
void Goo(System.IDisposable d)
{
[A]using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9));
}
[Fact]
public void AttributeOnLocalDeclOrMember8()
{
var test = UsingTree(@"
class C
{
void Goo(System.IAsyncDisposable d)
{
[A]await using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IAsyncDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,21): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?)
// void Goo(System.IAsyncDisposable d)
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 21),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12),
// (6,12): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12));
}
[Fact]
public void AttributeOnLocalDeclOrMember9()
{
var test = UsingTree(@"
class C
{
async void Goo(System.IAsyncDisposable d)
{
[A]await using var i = d;
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Goo");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "System");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "IAsyncDisposable");
}
}
N(SyntaxKind.IdentifierToken, "d");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.UsingKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
CreateCompilation(test).GetDiagnostics().Verify(
// (4,27): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?)
// async void Goo(System.IAsyncDisposable d)
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 27),
// (6,9): error CS7014: Attributes are not valid in this context.
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9),
// (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// [A]await using var i = d;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12));
}
[Fact]
public void AttrDeclOnStatementWhereMemberExpected()
{
UsingTree(@"
class C
{
[Attr] x.y();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Attr");
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
M(SyntaxKind.TupleElement);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CommaToken);
M(SyntaxKind.TupleElement);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/Symbol/Compilation/ForEachStatementInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class ForEachStatementInfoTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c = (Compilation)CreateCompilation(@"
class E1
{
public E GetEnumerator() { return null; }
public bool MoveNext() { return false; }
public object Current { get; }
public void Dispose() { }
}
class E2
{
public E GetEnumerator() { return null; }
public bool MoveNext() { return false; }
public object Current { get; }
public void Dispose() { }
}
");
var e1 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E1").Single();
var ge1 = (IMethodSymbol)e1.GetMembers("GetEnumerator").Single();
var mn1 = (IMethodSymbol)e1.GetMembers("MoveNext").Single();
var cur1 = (IPropertySymbol)e1.GetMembers("Current").Single();
var disp1 = (IMethodSymbol)e1.GetMembers("Dispose").Single();
var conv1 = Conversion.Identity;
var e2 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E2").Single();
var ge2 = (IMethodSymbol)e2.GetMembers("GetEnumerator").Single();
var mn2 = (IMethodSymbol)e2.GetMembers("MoveNext").Single();
var cur2 = (IPropertySymbol)e2.GetMembers("Current").Single();
var disp2 = (IMethodSymbol)e2.GetMembers("Dispose").Single();
var conv2 = Conversion.NoConversion;
EqualityTesting.AssertEqual(default(ForEachStatementInfo), default(ForEachStatementInfo));
EqualityTesting.AssertEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge2, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn2, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur2, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp2, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv2, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv2), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: false, ge1, mn1, cur1, disp1, e1, conv1, conv1));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class ForEachStatementInfoTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c = (Compilation)CreateCompilation(@"
class E1
{
public E GetEnumerator() { return null; }
public bool MoveNext() { return false; }
public object Current { get; }
public void Dispose() { }
}
class E2
{
public E GetEnumerator() { return null; }
public bool MoveNext() { return false; }
public object Current { get; }
public void Dispose() { }
}
");
var e1 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E1").Single();
var ge1 = (IMethodSymbol)e1.GetMembers("GetEnumerator").Single();
var mn1 = (IMethodSymbol)e1.GetMembers("MoveNext").Single();
var cur1 = (IPropertySymbol)e1.GetMembers("Current").Single();
var disp1 = (IMethodSymbol)e1.GetMembers("Dispose").Single();
var conv1 = Conversion.Identity;
var e2 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E2").Single();
var ge2 = (IMethodSymbol)e2.GetMembers("GetEnumerator").Single();
var mn2 = (IMethodSymbol)e2.GetMembers("MoveNext").Single();
var cur2 = (IPropertySymbol)e2.GetMembers("Current").Single();
var disp2 = (IMethodSymbol)e2.GetMembers("Dispose").Single();
var conv2 = Conversion.NoConversion;
EqualityTesting.AssertEqual(default(ForEachStatementInfo), default(ForEachStatementInfo));
EqualityTesting.AssertEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge2, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn2, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur2, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp2, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv2, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv2), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1));
EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: false, ge1, mn1, cur1, disp1, e1, conv1, conv1));
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundLateInvocation.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Diagnostics
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLateInvocation
''' <summary>
''' Updates access kind. To clear the access kind,
''' 'newAccessKind' should be Unknown. Otherwise, the current
''' access kind should be Unknown or equal to 'newAccessKind'.
''' </summary>
Public Function SetAccessKind(newAccessKind As LateBoundAccessKind) As BoundLateInvocation
Debug.Assert(newAccessKind = LateBoundAccessKind.Unknown OrElse
Me.AccessKind = LateBoundAccessKind.Unknown OrElse
Me.AccessKind = newAccessKind)
Dim member As BoundExpression = Me.Member
If member.Kind = BoundKind.LateMemberAccess Then
member = DirectCast(member, BoundLateMemberAccess).SetAccessKind(newAccessKind)
End If
Return Me.Update(member, Me.ArgumentsOpt, Me.ArgumentNamesOpt, newAccessKind, Me.MethodOrPropertyGroupOpt, Me.Type)
End Function
#If DEBUG Then
Private Sub Validate()
Debug.Assert((AccessKind And LateBoundAccessKind.Call) = 0 OrElse (AccessKind And Not LateBoundAccessKind.Call) = 0)
If Member.Kind = BoundKind.LateMemberAccess Then
Debug.Assert(DirectCast(Member, BoundLateMemberAccess).AccessKind = Me.AccessKind)
End If
Debug.Assert(Type.IsObjectType())
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Diagnostics
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLateInvocation
''' <summary>
''' Updates access kind. To clear the access kind,
''' 'newAccessKind' should be Unknown. Otherwise, the current
''' access kind should be Unknown or equal to 'newAccessKind'.
''' </summary>
Public Function SetAccessKind(newAccessKind As LateBoundAccessKind) As BoundLateInvocation
Debug.Assert(newAccessKind = LateBoundAccessKind.Unknown OrElse
Me.AccessKind = LateBoundAccessKind.Unknown OrElse
Me.AccessKind = newAccessKind)
Dim member As BoundExpression = Me.Member
If member.Kind = BoundKind.LateMemberAccess Then
member = DirectCast(member, BoundLateMemberAccess).SetAccessKind(newAccessKind)
End If
Return Me.Update(member, Me.ArgumentsOpt, Me.ArgumentNamesOpt, newAccessKind, Me.MethodOrPropertyGroupOpt, Me.Type)
End Function
#If DEBUG Then
Private Sub Validate()
Debug.Assert((AccessKind And LateBoundAccessKind.Call) = 0 OrElse (AccessKind And Not LateBoundAccessKind.Call) = 0)
If Member.Kind = BoundKind.LateMemberAccess Then
Debug.Assert(DirectCast(Member, BoundLateMemberAccess).AccessKind = Me.AccessKind)
End If
Debug.Assert(Type.IsObjectType())
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Tools/AnalyzerRunner/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild;
namespace AnalyzerRunner
{
/// <summary>
/// AnalyzerRunner is a tool that will analyze a solution, find diagnostics in it and will print out the number of
/// diagnostics it could find. This is useful to easily test performance without having the overhead of visual
/// studio running.
/// </summary>
class Program
{
public static async Task Main(string[] args)
{
Options options;
try
{
options = Options.Create(args);
}
catch (InvalidDataException)
{
PrintHelp();
return;
}
var cts = new CancellationTokenSource();
Console.CancelKeyPress +=
(sender, e) =>
{
e.Cancel = true;
cts.Cancel();
};
var cancellationToken = cts.Token;
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
Directory.CreateDirectory(options.ProfileRoot);
ProfileOptimization.SetProfileRoot(options.ProfileRoot);
}
using var workspace = AnalyzerRunnerHelper.CreateWorkspace();
var incrementalAnalyzerRunner = new IncrementalAnalyzerRunner(workspace, options);
var diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(workspace, options);
var codeRefactoringRunner = new CodeRefactoringRunner(workspace, options);
if (!incrementalAnalyzerRunner.HasAnalyzers && !diagnosticAnalyzerRunner.HasAnalyzers && !codeRefactoringRunner.HasRefactorings)
{
WriteLine("No analyzers found", ConsoleColor.Red);
PrintHelp();
return;
}
var stopwatch = PerformanceTracker.StartNew();
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(MSBuildWorkspace.OpenSolutionAsync));
}
await workspace.OpenSolutionAsync(options.SolutionPath, progress: null, cancellationToken).ConfigureAwait(false);
foreach (var workspaceDiagnostic in workspace.Diagnostics)
{
if (workspaceDiagnostic.Kind == WorkspaceDiagnosticKind.Failure)
{
Console.WriteLine(workspaceDiagnostic.Message);
}
}
Console.WriteLine($"Loaded solution in {stopwatch.GetSummary(preciseMemory: true)}");
if (options.ShowStats)
{
stopwatch = PerformanceTracker.StartNew();
ShowSolutionStatistics(workspace.CurrentSolution, cancellationToken);
Console.WriteLine($"Statistics gathered in {stopwatch.GetSummary(preciseMemory: true)}");
}
if (options.ShowCompilerDiagnostics)
{
await ShowCompilerDiagnosticsAsync(workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
}
Console.WriteLine("Pausing 5 seconds before starting analysis...");
await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
if (incrementalAnalyzerRunner.HasAnalyzers)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(Microsoft.CodeAnalysis.SolutionCrawler.IIncrementalAnalyzer));
}
await incrementalAnalyzerRunner.RunAsync(cancellationToken).ConfigureAwait(false);
}
if (diagnosticAnalyzerRunner.HasAnalyzers)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(DiagnosticAnalyzerRunner));
}
await diagnosticAnalyzerRunner.RunAllAsync(cancellationToken).ConfigureAwait(false);
}
if (codeRefactoringRunner.HasRefactorings)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(CodeRefactoringRunner));
}
await codeRefactoringRunner.RunAsync(cancellationToken).ConfigureAwait(false);
}
}
private static async Task ShowCompilerDiagnosticsAsync(Solution solution, CancellationToken cancellationToken)
{
var projectIds = solution.ProjectIds;
foreach (var projectId in projectIds)
{
solution = solution.WithProjectAnalyzerReferences(projectId, ImmutableArray<AnalyzerReference>.Empty);
}
var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList();
var diagnosticStatistics = new Dictionary<string, (string description, DiagnosticSeverity severity, int count)>();
foreach (var project in projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in compilation.GetDiagnostics(cancellationToken))
{
diagnosticStatistics.TryGetValue(diagnostic.Id, out var existing);
var description = existing.description;
if (string.IsNullOrEmpty(description))
{
description = diagnostic.Descriptor?.Title.ToString();
if (string.IsNullOrEmpty(description))
{
description = diagnostic.Descriptor?.MessageFormat.ToString();
}
}
diagnosticStatistics[diagnostic.Id] = (description, diagnostic.Descriptor.DefaultSeverity, existing.count + 1);
}
}
foreach (var pair in diagnosticStatistics)
{
Console.WriteLine($" {pair.Value.severity} {pair.Key}: {pair.Value.count} instances ({pair.Value.description})");
}
}
private static void ShowSolutionStatistics(Solution solution, CancellationToken cancellationToken)
{
var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList();
Console.WriteLine("Number of projects:\t\t" + projects.Count);
Console.WriteLine("Number of documents:\t\t" + projects.Sum(x => x.DocumentIds.Count));
var statistics = GetSolutionStatistics(projects, cancellationToken);
Console.WriteLine("Number of syntax nodes:\t\t" + statistics.NumberofNodes);
Console.WriteLine("Number of syntax tokens:\t" + statistics.NumberOfTokens);
Console.WriteLine("Number of syntax trivia:\t" + statistics.NumberOfTrivia);
}
private static Statistic GetSolutionStatistics(IEnumerable<Project> projects, CancellationToken cancellationToken)
{
var sums = new ConcurrentBag<Statistic>();
Parallel.ForEach(projects.SelectMany(project => project.Documents), document =>
{
var documentStatistics = GetSolutionStatisticsAsync(document, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
sums.Add(documentStatistics);
});
var sum = sums.Aggregate(new Statistic(0, 0, 0), (currentResult, value) => currentResult + value);
return sum;
}
// TODO consider removing this and using GetAnalysisResultAsync
// https://github.com/dotnet/roslyn/issues/23108
private static async Task<Statistic> GetSolutionStatisticsAsync(Document document, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var tokensAndNodes = root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true);
var numberOfNodes = tokensAndNodes.Count(x => x.IsNode);
var numberOfTokens = tokensAndNodes.Count(x => x.IsToken);
var numberOfTrivia = root.DescendantTrivia(descendIntoTrivia: true).Count();
return new Statistic(numberOfNodes, numberOfTokens, numberOfTrivia);
}
internal static void WriteLine(string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
internal static void PrintHelp()
{
Console.WriteLine("Usage: AnalyzerRunner <AnalyzerAssemblyOrFolder> <Solution> [options]");
Console.WriteLine("Options:");
Console.WriteLine("/all Run all analyzers, including ones that are disabled by default");
Console.WriteLine("/stats Display statistics of the solution");
Console.WriteLine("/a <analyzer name> Enable analyzer with <analyzer name> (when this is specified, only analyzers specificed are enabled. Use: /a <name1> /a <name2>, etc.");
Console.WriteLine("/concurrent Executes analyzers in concurrent mode");
Console.WriteLine("/suppressed Reports suppressed diagnostics");
Console.WriteLine("/log <logFile> Write logs into the log file specified");
Console.WriteLine("/editperf[:<match>] Test the incremental performance of analyzers to simulate the behavior of editing files. If <match> is specified, only files matching this regular expression are evaluated for editor performance.");
Console.WriteLine("/edititer:<iterations> Specifies the number of iterations to use for testing documents with /editperf. When this is not specified, the default value is 10.");
Console.WriteLine("/persist Enable persistent storage (e.g. SQLite; only applies to IIncrementalAnalyzer testing)");
Console.WriteLine("/fsa Enable full solution analysis (only applies to IIncrementalAnalyzer testing)");
Console.WriteLine("/ia <analyzer name> Enable incremental analyzer with <analyzer name> (when this is specified, only incremental analyzers specified are enabled. Use: /ia <name1> /ia <name2>, etc.");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild;
namespace AnalyzerRunner
{
/// <summary>
/// AnalyzerRunner is a tool that will analyze a solution, find diagnostics in it and will print out the number of
/// diagnostics it could find. This is useful to easily test performance without having the overhead of visual
/// studio running.
/// </summary>
class Program
{
public static async Task Main(string[] args)
{
Options options;
try
{
options = Options.Create(args);
}
catch (InvalidDataException)
{
PrintHelp();
return;
}
var cts = new CancellationTokenSource();
Console.CancelKeyPress +=
(sender, e) =>
{
e.Cancel = true;
cts.Cancel();
};
var cancellationToken = cts.Token;
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
Directory.CreateDirectory(options.ProfileRoot);
ProfileOptimization.SetProfileRoot(options.ProfileRoot);
}
using var workspace = AnalyzerRunnerHelper.CreateWorkspace();
var incrementalAnalyzerRunner = new IncrementalAnalyzerRunner(workspace, options);
var diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(workspace, options);
var codeRefactoringRunner = new CodeRefactoringRunner(workspace, options);
if (!incrementalAnalyzerRunner.HasAnalyzers && !diagnosticAnalyzerRunner.HasAnalyzers && !codeRefactoringRunner.HasRefactorings)
{
WriteLine("No analyzers found", ConsoleColor.Red);
PrintHelp();
return;
}
var stopwatch = PerformanceTracker.StartNew();
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(MSBuildWorkspace.OpenSolutionAsync));
}
await workspace.OpenSolutionAsync(options.SolutionPath, progress: null, cancellationToken).ConfigureAwait(false);
foreach (var workspaceDiagnostic in workspace.Diagnostics)
{
if (workspaceDiagnostic.Kind == WorkspaceDiagnosticKind.Failure)
{
Console.WriteLine(workspaceDiagnostic.Message);
}
}
Console.WriteLine($"Loaded solution in {stopwatch.GetSummary(preciseMemory: true)}");
if (options.ShowStats)
{
stopwatch = PerformanceTracker.StartNew();
ShowSolutionStatistics(workspace.CurrentSolution, cancellationToken);
Console.WriteLine($"Statistics gathered in {stopwatch.GetSummary(preciseMemory: true)}");
}
if (options.ShowCompilerDiagnostics)
{
await ShowCompilerDiagnosticsAsync(workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
}
Console.WriteLine("Pausing 5 seconds before starting analysis...");
await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
if (incrementalAnalyzerRunner.HasAnalyzers)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(Microsoft.CodeAnalysis.SolutionCrawler.IIncrementalAnalyzer));
}
await incrementalAnalyzerRunner.RunAsync(cancellationToken).ConfigureAwait(false);
}
if (diagnosticAnalyzerRunner.HasAnalyzers)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(DiagnosticAnalyzerRunner));
}
await diagnosticAnalyzerRunner.RunAllAsync(cancellationToken).ConfigureAwait(false);
}
if (codeRefactoringRunner.HasRefactorings)
{
if (!string.IsNullOrEmpty(options.ProfileRoot))
{
ProfileOptimization.StartProfile(nameof(CodeRefactoringRunner));
}
await codeRefactoringRunner.RunAsync(cancellationToken).ConfigureAwait(false);
}
}
private static async Task ShowCompilerDiagnosticsAsync(Solution solution, CancellationToken cancellationToken)
{
var projectIds = solution.ProjectIds;
foreach (var projectId in projectIds)
{
solution = solution.WithProjectAnalyzerReferences(projectId, ImmutableArray<AnalyzerReference>.Empty);
}
var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList();
var diagnosticStatistics = new Dictionary<string, (string description, DiagnosticSeverity severity, int count)>();
foreach (var project in projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in compilation.GetDiagnostics(cancellationToken))
{
diagnosticStatistics.TryGetValue(diagnostic.Id, out var existing);
var description = existing.description;
if (string.IsNullOrEmpty(description))
{
description = diagnostic.Descriptor?.Title.ToString();
if (string.IsNullOrEmpty(description))
{
description = diagnostic.Descriptor?.MessageFormat.ToString();
}
}
diagnosticStatistics[diagnostic.Id] = (description, diagnostic.Descriptor.DefaultSeverity, existing.count + 1);
}
}
foreach (var pair in diagnosticStatistics)
{
Console.WriteLine($" {pair.Value.severity} {pair.Key}: {pair.Value.count} instances ({pair.Value.description})");
}
}
private static void ShowSolutionStatistics(Solution solution, CancellationToken cancellationToken)
{
var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList();
Console.WriteLine("Number of projects:\t\t" + projects.Count);
Console.WriteLine("Number of documents:\t\t" + projects.Sum(x => x.DocumentIds.Count));
var statistics = GetSolutionStatistics(projects, cancellationToken);
Console.WriteLine("Number of syntax nodes:\t\t" + statistics.NumberofNodes);
Console.WriteLine("Number of syntax tokens:\t" + statistics.NumberOfTokens);
Console.WriteLine("Number of syntax trivia:\t" + statistics.NumberOfTrivia);
}
private static Statistic GetSolutionStatistics(IEnumerable<Project> projects, CancellationToken cancellationToken)
{
var sums = new ConcurrentBag<Statistic>();
Parallel.ForEach(projects.SelectMany(project => project.Documents), document =>
{
var documentStatistics = GetSolutionStatisticsAsync(document, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
sums.Add(documentStatistics);
});
var sum = sums.Aggregate(new Statistic(0, 0, 0), (currentResult, value) => currentResult + value);
return sum;
}
// TODO consider removing this and using GetAnalysisResultAsync
// https://github.com/dotnet/roslyn/issues/23108
private static async Task<Statistic> GetSolutionStatisticsAsync(Document document, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var tokensAndNodes = root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true);
var numberOfNodes = tokensAndNodes.Count(x => x.IsNode);
var numberOfTokens = tokensAndNodes.Count(x => x.IsToken);
var numberOfTrivia = root.DescendantTrivia(descendIntoTrivia: true).Count();
return new Statistic(numberOfNodes, numberOfTokens, numberOfTrivia);
}
internal static void WriteLine(string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
internal static void PrintHelp()
{
Console.WriteLine("Usage: AnalyzerRunner <AnalyzerAssemblyOrFolder> <Solution> [options]");
Console.WriteLine("Options:");
Console.WriteLine("/all Run all analyzers, including ones that are disabled by default");
Console.WriteLine("/stats Display statistics of the solution");
Console.WriteLine("/a <analyzer name> Enable analyzer with <analyzer name> (when this is specified, only analyzers specificed are enabled. Use: /a <name1> /a <name2>, etc.");
Console.WriteLine("/concurrent Executes analyzers in concurrent mode");
Console.WriteLine("/suppressed Reports suppressed diagnostics");
Console.WriteLine("/log <logFile> Write logs into the log file specified");
Console.WriteLine("/editperf[:<match>] Test the incremental performance of analyzers to simulate the behavior of editing files. If <match> is specified, only files matching this regular expression are evaluated for editor performance.");
Console.WriteLine("/edititer:<iterations> Specifies the number of iterations to use for testing documents with /editperf. When this is not specified, the default value is 10.");
Console.WriteLine("/persist Enable persistent storage (e.g. SQLite; only applies to IIncrementalAnalyzer testing)");
Console.WriteLine("/fsa Enable full solution analysis (only applies to IIncrementalAnalyzer testing)");
Console.WriteLine("/ia <analyzer name> Enable incremental analyzer with <analyzer name> (when this is specified, only incremental analyzers specified are enabled. Use: /ia <name1> /ia <name2>, etc.");
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/LanguageServer/Protocol/DefaultCapabilitiesProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Export(typeof(DefaultCapabilitiesProvider)), Shared]
internal class DefaultCapabilitiesProvider : ICapabilitiesProvider
{
private readonly ImmutableArray<Lazy<CompletionProvider, CompletionProviderMetadata>> _completionProviders;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultCapabilitiesProvider(
[ImportMany] IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders)
{
_completionProviders = completionProviders
.Where(lz => lz.Metadata.Language == LanguageNames.CSharp || lz.Metadata.Language == LanguageNames.VisualBasic)
.ToImmutableArray();
}
public ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
{
var capabilities = new ServerCapabilities();
if (clientCapabilities is VSInternalClientCapabilities vsClientCapabilities && vsClientCapabilities.SupportsVisualStudioExtensions)
{
capabilities = GetVSServerCapabilities();
}
var commitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray();
var triggerCharacters = _completionProviders.SelectMany(
lz => CompletionHandler.GetTriggerCharacters(lz.Value)).Distinct().Select(c => c.ToString()).ToArray();
capabilities.DefinitionProvider = true;
capabilities.RenameProvider = true;
capabilities.ImplementationProvider = true;
capabilities.CodeActionProvider = new CodeActionOptions { CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor }, ResolveProvider = true };
capabilities.CompletionProvider = new VisualStudio.LanguageServer.Protocol.CompletionOptions
{
ResolveProvider = true,
AllCommitCharacters = commitCharacters,
TriggerCharacters = triggerCharacters,
};
capabilities.SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } };
capabilities.DocumentSymbolProvider = true;
capabilities.WorkspaceSymbolProvider = true;
capabilities.DocumentFormattingProvider = true;
capabilities.DocumentRangeFormattingProvider = true;
capabilities.DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } };
capabilities.ReferencesProvider = true;
capabilities.FoldingRangeProvider = true;
capabilities.ExecuteCommandProvider = new ExecuteCommandOptions();
capabilities.TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.Incremental,
OpenClose = true
};
capabilities.HoverProvider = true;
capabilities.SemanticTokensOptions = new SemanticTokensOptions
{
Full = new SemanticTokensFullOptions { Delta = true },
Range = true,
Legend = new SemanticTokensLegend
{
TokenTypes = SemanticTokenTypes.AllTypes.Concat(SemanticTokensHelpers.RoslynCustomTokenTypes).ToArray(),
TokenModifiers = new string[] { SemanticTokenModifiers.Static }
}
};
return capabilities;
}
private static VSServerCapabilities GetVSServerCapabilities()
{
var vsServerCapabilities = new VSInternalServerCapabilities();
vsServerCapabilities.OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "'", "/", "\n" } };
vsServerCapabilities.DocumentHighlightProvider = true;
vsServerCapabilities.ProjectContextProvider = true;
// Diagnostic requests are only supported from PullDiagnosticsInProcLanguageClient.
vsServerCapabilities.SupportsDiagnosticRequests = false;
return vsServerCapabilities;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Export(typeof(DefaultCapabilitiesProvider)), Shared]
internal class DefaultCapabilitiesProvider : ICapabilitiesProvider
{
private readonly ImmutableArray<Lazy<CompletionProvider, CompletionProviderMetadata>> _completionProviders;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultCapabilitiesProvider(
[ImportMany] IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders)
{
_completionProviders = completionProviders
.Where(lz => lz.Metadata.Language == LanguageNames.CSharp || lz.Metadata.Language == LanguageNames.VisualBasic)
.ToImmutableArray();
}
public ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
{
var capabilities = new ServerCapabilities();
if (clientCapabilities is VSInternalClientCapabilities vsClientCapabilities && vsClientCapabilities.SupportsVisualStudioExtensions)
{
capabilities = GetVSServerCapabilities();
}
var commitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray();
var triggerCharacters = _completionProviders.SelectMany(
lz => CompletionHandler.GetTriggerCharacters(lz.Value)).Distinct().Select(c => c.ToString()).ToArray();
capabilities.DefinitionProvider = true;
capabilities.RenameProvider = true;
capabilities.ImplementationProvider = true;
capabilities.CodeActionProvider = new CodeActionOptions { CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor }, ResolveProvider = true };
capabilities.CompletionProvider = new VisualStudio.LanguageServer.Protocol.CompletionOptions
{
ResolveProvider = true,
AllCommitCharacters = commitCharacters,
TriggerCharacters = triggerCharacters,
};
capabilities.SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } };
capabilities.DocumentSymbolProvider = true;
capabilities.WorkspaceSymbolProvider = true;
capabilities.DocumentFormattingProvider = true;
capabilities.DocumentRangeFormattingProvider = true;
capabilities.DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } };
capabilities.ReferencesProvider = true;
capabilities.FoldingRangeProvider = true;
capabilities.ExecuteCommandProvider = new ExecuteCommandOptions();
capabilities.TextDocumentSync = new TextDocumentSyncOptions
{
Change = TextDocumentSyncKind.Incremental,
OpenClose = true
};
capabilities.HoverProvider = true;
capabilities.SemanticTokensOptions = new SemanticTokensOptions
{
Full = new SemanticTokensFullOptions { Delta = true },
Range = true,
Legend = new SemanticTokensLegend
{
TokenTypes = SemanticTokenTypes.AllTypes.Concat(SemanticTokensHelpers.RoslynCustomTokenTypes).ToArray(),
TokenModifiers = new string[] { SemanticTokenModifiers.Static }
}
};
return capabilities;
}
private static VSServerCapabilities GetVSServerCapabilities()
{
var vsServerCapabilities = new VSInternalServerCapabilities();
vsServerCapabilities.OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "'", "/", "\n" } };
vsServerCapabilities.DocumentHighlightProvider = true;
vsServerCapabilities.ProjectContextProvider = true;
// Diagnostic requests are only supported from PullDiagnosticsInProcLanguageClient.
vsServerCapabilities.SupportsDiagnosticRequests = false;
return vsServerCapabilities;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/LiveShare/Impl/Client/LanguageServiceUtils.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client
{
internal static class LanguageServicesUtils
{
private const string LanguageServerProviderServiceName = "languageServerProvider";
public static string GetLanguageServerProviderServiceName(string[] contentTypes)
{
Requires.NotNullOrEmpty(contentTypes, nameof(contentTypes));
return GetLanguageServerProviderServiceName(GetContentTypesName(contentTypes));
}
public static string GetLanguageServerProviderServiceName(string lspServiceName)
=> LanguageServerProviderServiceName + "-" + lspServiceName;
public static string GetContentTypesName(string[] contentTypes) => string.Join("-", contentTypes.OrderBy(c => c).ToArray());
public static bool IsContentTypeRemote(string contentType)
=> contentType.EndsWith("-remote");
public static bool TryParseJson<T>(object json, out T t)
{
t = default;
if (json == null)
{
return true;
}
try
{
t = ((JObject)json).ToObject<T>();
return true;
}
catch (JsonException)
{
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.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client
{
internal static class LanguageServicesUtils
{
private const string LanguageServerProviderServiceName = "languageServerProvider";
public static string GetLanguageServerProviderServiceName(string[] contentTypes)
{
Requires.NotNullOrEmpty(contentTypes, nameof(contentTypes));
return GetLanguageServerProviderServiceName(GetContentTypesName(contentTypes));
}
public static string GetLanguageServerProviderServiceName(string lspServiceName)
=> LanguageServerProviderServiceName + "-" + lspServiceName;
public static string GetContentTypesName(string[] contentTypes) => string.Join("-", contentTypes.OrderBy(c => c).ToArray());
public static bool IsContentTypeRemote(string contentType)
=> contentType.EndsWith("-remote");
public static bool TryParseJson<T>(object json, out T t)
{
t = default;
if (json == null)
{
return true;
}
try
{
t = ((JObject)json).ToObject<T>();
return true;
}
catch (JsonException)
{
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ImportCompletionItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Tags;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal static class ImportCompletionItem
{
private const string SortTextFormat = "{0} {1}";
private const string TypeAritySuffixName = nameof(TypeAritySuffixName);
private const string AttributeFullName = nameof(AttributeFullName);
private const string MethodKey = nameof(MethodKey);
private const string ReceiverKey = nameof(ReceiverKey);
private const string OverloadCountKey = nameof(OverloadCountKey);
public static CompletionItem Create(
string name,
int arity,
string containingNamespace,
Glyph glyph,
string genericTypeSuffix,
CompletionItemFlags flags,
(string methodSymbolKey, string receiverTypeSymbolKey, int overloadCount)? extensionMethodData,
bool includedInTargetTypeCompletion = false)
{
ImmutableDictionary<string, string>? properties = null;
if (extensionMethodData != null || arity > 0)
{
var builder = PooledDictionary<string, string>.GetInstance();
if (extensionMethodData.HasValue)
{
builder.Add(MethodKey, extensionMethodData.Value.methodSymbolKey);
builder.Add(ReceiverKey, extensionMethodData.Value.receiverTypeSymbolKey);
if (extensionMethodData.Value.overloadCount > 0)
{
builder.Add(OverloadCountKey, extensionMethodData.Value.overloadCount.ToString());
}
}
else
{
// We don't need arity to recover symbol if we already have SymbolKeyData or it's 0.
// (but it still needed below to decide whether to show generic suffix)
builder.Add(TypeAritySuffixName, ArityUtilities.GetMetadataAritySuffix(arity));
}
properties = builder.ToImmutableDictionaryAndFree();
}
// Use "<display name> <namespace>" as sort text. The space before namespace makes items with identical display name
// but from different namespace all show up in the list, it also makes sure item with shorter name shows first,
// e.g. 'SomeType` before 'SomeTypeWithLongerName'.
var sortTextBuilder = PooledStringBuilder.GetInstance();
sortTextBuilder.Builder.AppendFormat(SortTextFormat, name, containingNamespace);
var item = CompletionItem.Create(
displayText: name,
sortText: sortTextBuilder.ToStringAndFree(),
properties: properties,
tags: GlyphTags.GetTags(glyph),
rules: CompletionItemRules.Default,
displayTextPrefix: null,
displayTextSuffix: arity == 0 ? string.Empty : genericTypeSuffix,
inlineDescription: containingNamespace,
isComplexTextEdit: true);
if (includedInTargetTypeCompletion)
{
item = item.AddTag(WellKnownTags.TargetTypeMatch);
}
item.Flags = flags;
return item;
}
public static CompletionItem CreateAttributeItemWithoutSuffix(CompletionItem attributeItem, string attributeNameWithoutSuffix, CompletionItemFlags flags)
{
Debug.Assert(!attributeItem.Properties.ContainsKey(AttributeFullName));
// Remember the full type name so we can get the symbol when description is displayed.
var newProperties = attributeItem.Properties.Add(AttributeFullName, attributeItem.DisplayText);
var sortTextBuilder = PooledStringBuilder.GetInstance();
sortTextBuilder.Builder.AppendFormat(SortTextFormat, attributeNameWithoutSuffix, attributeItem.InlineDescription);
var item = CompletionItem.Create(
displayText: attributeNameWithoutSuffix,
sortText: sortTextBuilder.ToStringAndFree(),
properties: newProperties,
tags: attributeItem.Tags,
rules: attributeItem.Rules,
displayTextPrefix: attributeItem.DisplayTextPrefix,
displayTextSuffix: attributeItem.DisplayTextSuffix,
inlineDescription: attributeItem.InlineDescription,
isComplexTextEdit: true);
item.Flags = flags;
return item;
}
public static CompletionItem CreateItemWithGenericDisplaySuffix(CompletionItem item, string genericTypeSuffix)
=> item.WithDisplayTextSuffix(genericTypeSuffix);
public static string GetContainingNamespace(CompletionItem item)
=> item.InlineDescription;
public static async Task<CompletionDescription> GetCompletionDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
{
var compilation = (await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false));
var (symbol, overloadCount) = GetSymbolAndOverloadCount(item, compilation);
if (symbol != null)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await CommonCompletionUtilities.CreateDescriptionAsync(
document.Project.Solution.Workspace,
semanticModel,
position: 0,
symbol,
overloadCount,
supportedPlatforms: null,
cancellationToken).ConfigureAwait(false);
}
return CompletionDescription.Empty;
}
public static string GetTypeName(CompletionItem item)
{
var typeName = item.Properties.TryGetValue(AttributeFullName, out var attributeFullName)
? attributeFullName
: item.DisplayText;
if (item.Properties.TryGetValue(TypeAritySuffixName, out var aritySuffix))
{
return typeName + aritySuffix;
}
return typeName;
}
private static string GetFullyQualifiedName(string namespaceName, string typeName)
=> namespaceName.Length == 0 ? typeName : namespaceName + "." + typeName;
private static (ISymbol? symbol, int overloadCount) GetSymbolAndOverloadCount(CompletionItem item, Compilation compilation)
{
// If we have SymbolKey data (i.e. this is an extension method item), use it to recover symbol
if (item.Properties.TryGetValue(MethodKey, out var methodSymbolKey))
{
var methodSymbol = SymbolKey.ResolveString(methodSymbolKey, compilation).GetAnySymbol() as IMethodSymbol;
if (methodSymbol != null)
{
var overloadCount = item.Properties.TryGetValue(OverloadCountKey, out var overloadCountString) && int.TryParse(overloadCountString, out var count) ? count : 0;
// Get reduced extension method symbol for the given receiver type.
if (item.Properties.TryGetValue(ReceiverKey, out var receiverTypeKey))
{
if (SymbolKey.ResolveString(receiverTypeKey, compilation).GetAnySymbol() is ITypeSymbol receiverTypeSymbol)
{
return (methodSymbol.ReduceExtensionMethod(receiverTypeSymbol) ?? methodSymbol, overloadCount);
}
}
return (methodSymbol, overloadCount);
}
return default;
}
// Otherwise, this is a type item, so we don't have SymbolKey data. But we should still have all
// the data to construct its full metadata name
var containingNamespace = GetContainingNamespace(item);
var typeName = item.Properties.TryGetValue(AttributeFullName, out var attributeFullName) ? attributeFullName : item.DisplayText;
var fullyQualifiedName = GetFullyQualifiedName(containingNamespace, typeName);
// We choose not to display the number of "type overloads" for simplicity.
// Otherwise, we need additional logic to track internal and public visible
// types separately, and cache both completion items.
if (item.Properties.TryGetValue(TypeAritySuffixName, out var aritySuffix))
{
return (compilation.GetTypeByMetadataName(fullyQualifiedName + aritySuffix), 0);
}
return (compilation.GetTypeByMetadataName(fullyQualifiedName), 0);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Tags;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal static class ImportCompletionItem
{
private const string SortTextFormat = "{0} {1}";
private const string TypeAritySuffixName = nameof(TypeAritySuffixName);
private const string AttributeFullName = nameof(AttributeFullName);
private const string MethodKey = nameof(MethodKey);
private const string ReceiverKey = nameof(ReceiverKey);
private const string OverloadCountKey = nameof(OverloadCountKey);
public static CompletionItem Create(
string name,
int arity,
string containingNamespace,
Glyph glyph,
string genericTypeSuffix,
CompletionItemFlags flags,
(string methodSymbolKey, string receiverTypeSymbolKey, int overloadCount)? extensionMethodData,
bool includedInTargetTypeCompletion = false)
{
ImmutableDictionary<string, string>? properties = null;
if (extensionMethodData != null || arity > 0)
{
var builder = PooledDictionary<string, string>.GetInstance();
if (extensionMethodData.HasValue)
{
builder.Add(MethodKey, extensionMethodData.Value.methodSymbolKey);
builder.Add(ReceiverKey, extensionMethodData.Value.receiverTypeSymbolKey);
if (extensionMethodData.Value.overloadCount > 0)
{
builder.Add(OverloadCountKey, extensionMethodData.Value.overloadCount.ToString());
}
}
else
{
// We don't need arity to recover symbol if we already have SymbolKeyData or it's 0.
// (but it still needed below to decide whether to show generic suffix)
builder.Add(TypeAritySuffixName, ArityUtilities.GetMetadataAritySuffix(arity));
}
properties = builder.ToImmutableDictionaryAndFree();
}
// Use "<display name> <namespace>" as sort text. The space before namespace makes items with identical display name
// but from different namespace all show up in the list, it also makes sure item with shorter name shows first,
// e.g. 'SomeType` before 'SomeTypeWithLongerName'.
var sortTextBuilder = PooledStringBuilder.GetInstance();
sortTextBuilder.Builder.AppendFormat(SortTextFormat, name, containingNamespace);
var item = CompletionItem.Create(
displayText: name,
sortText: sortTextBuilder.ToStringAndFree(),
properties: properties,
tags: GlyphTags.GetTags(glyph),
rules: CompletionItemRules.Default,
displayTextPrefix: null,
displayTextSuffix: arity == 0 ? string.Empty : genericTypeSuffix,
inlineDescription: containingNamespace,
isComplexTextEdit: true);
if (includedInTargetTypeCompletion)
{
item = item.AddTag(WellKnownTags.TargetTypeMatch);
}
item.Flags = flags;
return item;
}
public static CompletionItem CreateAttributeItemWithoutSuffix(CompletionItem attributeItem, string attributeNameWithoutSuffix, CompletionItemFlags flags)
{
Debug.Assert(!attributeItem.Properties.ContainsKey(AttributeFullName));
// Remember the full type name so we can get the symbol when description is displayed.
var newProperties = attributeItem.Properties.Add(AttributeFullName, attributeItem.DisplayText);
var sortTextBuilder = PooledStringBuilder.GetInstance();
sortTextBuilder.Builder.AppendFormat(SortTextFormat, attributeNameWithoutSuffix, attributeItem.InlineDescription);
var item = CompletionItem.Create(
displayText: attributeNameWithoutSuffix,
sortText: sortTextBuilder.ToStringAndFree(),
properties: newProperties,
tags: attributeItem.Tags,
rules: attributeItem.Rules,
displayTextPrefix: attributeItem.DisplayTextPrefix,
displayTextSuffix: attributeItem.DisplayTextSuffix,
inlineDescription: attributeItem.InlineDescription,
isComplexTextEdit: true);
item.Flags = flags;
return item;
}
public static CompletionItem CreateItemWithGenericDisplaySuffix(CompletionItem item, string genericTypeSuffix)
=> item.WithDisplayTextSuffix(genericTypeSuffix);
public static string GetContainingNamespace(CompletionItem item)
=> item.InlineDescription;
public static async Task<CompletionDescription> GetCompletionDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
{
var compilation = (await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false));
var (symbol, overloadCount) = GetSymbolAndOverloadCount(item, compilation);
if (symbol != null)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await CommonCompletionUtilities.CreateDescriptionAsync(
document.Project.Solution.Workspace,
semanticModel,
position: 0,
symbol,
overloadCount,
supportedPlatforms: null,
cancellationToken).ConfigureAwait(false);
}
return CompletionDescription.Empty;
}
public static string GetTypeName(CompletionItem item)
{
var typeName = item.Properties.TryGetValue(AttributeFullName, out var attributeFullName)
? attributeFullName
: item.DisplayText;
if (item.Properties.TryGetValue(TypeAritySuffixName, out var aritySuffix))
{
return typeName + aritySuffix;
}
return typeName;
}
private static string GetFullyQualifiedName(string namespaceName, string typeName)
=> namespaceName.Length == 0 ? typeName : namespaceName + "." + typeName;
private static (ISymbol? symbol, int overloadCount) GetSymbolAndOverloadCount(CompletionItem item, Compilation compilation)
{
// If we have SymbolKey data (i.e. this is an extension method item), use it to recover symbol
if (item.Properties.TryGetValue(MethodKey, out var methodSymbolKey))
{
var methodSymbol = SymbolKey.ResolveString(methodSymbolKey, compilation).GetAnySymbol() as IMethodSymbol;
if (methodSymbol != null)
{
var overloadCount = item.Properties.TryGetValue(OverloadCountKey, out var overloadCountString) && int.TryParse(overloadCountString, out var count) ? count : 0;
// Get reduced extension method symbol for the given receiver type.
if (item.Properties.TryGetValue(ReceiverKey, out var receiverTypeKey))
{
if (SymbolKey.ResolveString(receiverTypeKey, compilation).GetAnySymbol() is ITypeSymbol receiverTypeSymbol)
{
return (methodSymbol.ReduceExtensionMethod(receiverTypeSymbol) ?? methodSymbol, overloadCount);
}
}
return (methodSymbol, overloadCount);
}
return default;
}
// Otherwise, this is a type item, so we don't have SymbolKey data. But we should still have all
// the data to construct its full metadata name
var containingNamespace = GetContainingNamespace(item);
var typeName = item.Properties.TryGetValue(AttributeFullName, out var attributeFullName) ? attributeFullName : item.DisplayText;
var fullyQualifiedName = GetFullyQualifiedName(containingNamespace, typeName);
// We choose not to display the number of "type overloads" for simplicity.
// Otherwise, we need additional logic to track internal and public visible
// types separately, and cache both completion items.
if (item.Properties.TryGetValue(TypeAritySuffixName, out var aritySuffix))
{
return (compilation.GetTypeByMetadataName(fullyQualifiedName + aritySuffix), 0);
}
return (compilation.GetTypeByMetadataName(fullyQualifiedName), 0);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/BaseClassTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Retargeting = Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class BaseClassTests : CSharpTestBase
{
[Fact]
public void CyclicBases1()
{
var text =
@"
class X : Y {}
class Y : X {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var y = global.GetTypeMembers("Y", 0).Single();
Assert.NotEqual(y, x.BaseType());
Assert.NotEqual(x, y.BaseType());
Assert.Equal(SymbolKind.ErrorType, x.BaseType().Kind);
Assert.Equal(SymbolKind.ErrorType, y.BaseType().Kind);
Assert.Equal("Y", x.BaseType().Name);
Assert.Equal("X", y.BaseType().Name);
}
[Fact]
public void CyclicBases2()
{
var text =
@"
class X : Y.n {}
class Y : X.n {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var y = global.GetTypeMembers("Y", 0).Single();
Assert.NotEqual(y, x.BaseType());
Assert.NotEqual(x, y.BaseType());
Assert.Equal(SymbolKind.ErrorType, x.BaseType().Kind);
Assert.Equal(SymbolKind.ErrorType, y.BaseType().Kind);
Assert.Equal("n", x.BaseType().Name);
Assert.Equal("n", y.BaseType().Name);
}
[Fact]
public void CyclicBases3()
{
var C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1;
var C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2;
var text =
@"
class C4 : C1 {}
";
var comp = CreateCompilation(text, new[] { C1, C2 });
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("C4", 0).Single();
var x_base_base = x.BaseType().BaseType() as ErrorTypeSymbol;
var er = x_base_base.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'C2' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(538506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538506")]
[Fact]
public void CyclicBasesRegress4140()
{
var text =
@"
class A<T>
{
class B : A<E> { }
class E : B.E { }
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 1).Single();
var b = a.GetTypeMembers("B", 0).Single();
var e = a.GetTypeMembers("E", 0).Single();
Assert.NotEqual(e, e.BaseType());
var x_base = e.BaseType() as ErrorTypeSymbol;
var er = x_base.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'A<A<T>.E>.E' and 'A<T>.E'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(538526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538526")]
[Fact]
public void CyclicBasesRegress4166()
{
var text =
@"
class A<T> {
public class C : B.D { }
}
class B {
public class D : A<int>.C { }
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 1).Single();
var b = global.GetTypeMembers("B", 0).Single();
var d = b.GetTypeMembers("D", 0).Single();
Assert.NotEqual(d, d.BaseType());
var x_base = d.BaseType() as ErrorTypeSymbol;
var er = x_base.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'A<int>.C' and 'B.D'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(4169, "DevDiv_Projects/Roslyn")]
[Fact]
public void CyclicBasesRegress4169()
{
var text =
@"
class A : object, A.IC
{
protected interface IC { }
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var ic = a.GetTypeMembers("IC", 0).Single();
Assert.Equal(a.Interfaces()[0], ic);
var diagnostics = comp.GetDeclarationDiagnostics();
Assert.Equal(0, diagnostics.Count());
}
[WorkItem(527551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527551")]
[Fact]
public void CyclicBasesRegress4168()
{
var text =
@"
class A : object, A.B.B.IC
{
public class B : A {
public interface IC { }
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var b = a.GetTypeMembers("B", 0).Single();
var ic = b.GetTypeMembers("IC", 0).Single();
Assert.NotEqual(b, b.BaseType());
Assert.NotEqual(a, b.BaseType());
Assert.Equal(SymbolKind.ErrorType, a.Interfaces()[0].Kind);
Assert.NotEqual(ic, a.Interfaces()[0]);
var diagnostics = comp.GetDeclarationDiagnostics();
Assert.Equal(2, diagnostics.Count());
}
[Fact]
public void CyclicBases4()
{
var text =
@"
class A<T> : B<A<T>> { }
class B<T> : A<B<T>> {
A<T> F() { return null; }
}
";
var comp = CreateCompilation(text);
comp.GetDeclarationDiagnostics().Verify(
// (2,7): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>'
// class A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>"),
// (3,7): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>'
// class B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>")
);
}
[Fact]
public void CyclicBases5()
{
// bases are cyclic, but you can still find members when binding bases
var text =
@"
class A : B {
public class X { }
}
class B : A {
public class Y { }
}
class Z : A.Y { }
class W : B.X { }
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var z = global.GetTypeMembers("Z", 0).Single();
var w = global.GetTypeMembers("W", 0).Single();
var zBase = z.BaseType();
Assert.Equal("Y", zBase.Name);
var wBase = w.BaseType();
Assert.Equal("X", wBase.Name);
}
[Fact]
public void CyclicBases6()
{
// bases are cyclic, but you can still search for members w/o infinite looping in binder
var text =
@"
class A : B {
public class X {}
}
class B : C {
public class Y {}
}
class C : A {
public class Z {}
}
";
var comp = (Compilation)CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
//var aBase = a.BaseType();
//Assert.True(aBase.IsErrorType());
//Assert.Equal("B", aBase.Name);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var classA = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
var someMemberInA = classA.Members[0];
int positionInA = someMemberInA.SpanStart;
var members = model.LookupSymbols(positionInA, a, "Z");
Assert.Equal(1, members.Length);
Assert.False(((ITypeSymbol)members[0]).IsErrorType());
Assert.Equal("C.Z", members[0].ToTestDisplayString());
var members2 = model.LookupSymbols(positionInA, a, "Q");
Assert.Equal(0, members2.Length);
}
[Fact]
public void CyclicBases7()
{
// bases are cyclic, but you can still search for members w/o infinite looping in binder
var text =
@"
class A : B<A.Y> {
public class X {}
}
class B<T> : A {
public class Y {}
}
";
var comp = (Compilation)CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
//var aBase = a.BaseType();
//Assert.True(aBase.IsErrorType());
//Assert.Equal("B", aBase.Name);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var classA = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
var someMemberInA = classA.Members[0];
int positionInA = someMemberInA.SpanStart;
var members = model.LookupSymbols(positionInA, a, "Q");
Assert.Equal(0, members.Length);
}
[Fact]
public void CyclicBases8()
{
var text = @"
public class A
{
protected class B
{
protected class C
{
public class X { }
}
}
}
internal class F : A
{
private class D : B
{
public class E : C.X { }
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (16,22): error CS0060: Inconsistent accessibility: base type 'A.B.C.X' is less accessible than class 'F.D.E'
// public class E : C.X { }
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "E").WithArguments("F.D.E", "A.B.C.X")
);
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void BadVisibilityPartial()
{
var text = @"
internal class NV
{
}
public partial class C1
{
}
partial class C1 : NV
{
}
public partial class C1
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (10,15): error CS0060: Inconsistent accessibility: base type 'NV' is less accessible than class 'C1'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 15));
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void StaticBasePartial()
{
var text = @"
static class NV
{
}
public partial class C1
{
}
partial class C1 : NV
{
}
public partial class C1
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (10,15): error CS0709: 'C1': cannot derive from static class 'NV'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_StaticBaseClass, "C1").WithArguments("NV", "C1").WithLocation(10, 15),
// (10,15): error CS0060: Inconsistent accessibility: base type 'NV' is less accessible than class 'C1'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 15));
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void BadVisInterfacePartial()
{
var text = @"
interface IGoo
{
void Moo();
}
interface IBaz
{
void Noo();
}
interface IBam
{
void Zoo();
}
public partial interface IBar
{
}
partial interface IBar : IGoo, IBam
{
}
partial interface IBar : IBaz, IBaz
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (25,32): error CS0528: 'IBaz' is already listed in interface list
// partial interface IBar : IBaz, IBaz
Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "IBaz").WithArguments("IBaz").WithLocation(25, 32),
// (21,19): error CS0061: Inconsistent accessibility: base interface 'IGoo' is less accessible than interface 'IBar'
// partial interface IBar : IGoo, IBam
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IGoo").WithLocation(21, 19),
// (21,19): error CS0061: Inconsistent accessibility: base interface 'IBam' is less accessible than interface 'IBar'
// partial interface IBar : IGoo, IBam
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IBam").WithLocation(21, 19),
// (25,19): error CS0061: Inconsistent accessibility: base interface 'IBaz' is less accessible than interface 'IBar'
// partial interface IBar : IBaz, IBaz
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IBaz").WithLocation(25, 19));
}
[Fact]
public void EricLiCase1()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class A {
public class B {}
}
class C : A, I<C.B> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single();
var cBase = c.BaseType();
Assert.False(cBase.IsErrorType());
Assert.Equal("A", cBase.Name);
Assert.True(c.Interfaces().Single().TypeArguments().Single().IsErrorType()); //can't see base of C while evaluating C.B
}
[Fact]
public void EricLiCase2()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class E : I<E> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var e = global.GetTypeMembers("E", 0).Single();
Assert.Equal(1, e.Interfaces().Length);
Assert.Equal("I<E>", e.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase3()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class G : I<G.H> {
public class H {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var g = global.GetTypeMembers("G", 0).Single();
Assert.Equal(1, g.Interfaces().Length);
Assert.Equal("I<G.H>", g.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase4()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class J : I<J.K.L> {
public class K {
public class L {}
}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var j = global.GetTypeMembers("J", 0).Single();
Assert.Equal(1, j.Interfaces().Length);
Assert.Equal("I<J.K.L>", j.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase5()
{
// should be cyclic
var text =
@"class M : M {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var m = global.GetTypeMembers("M", 0).Single();
Assert.True(m.BaseType().IsErrorType());
}
[Fact]
public void EricLiCase6()
{
// should not be cyclic
var text =
@"
class N<T> {}
class O : N<O> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var o = global.GetTypeMembers("O", 0).Single();
Assert.False(o.BaseType().IsErrorType());
Assert.Equal("N<O>", o.BaseType().ToTestDisplayString());
}
[Fact]
public void EricLiCase7()
{
// should not be cyclic
var text =
@"
class N<T> {}
class P : N<P.Q> {
public class Q {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var p = global.GetTypeMembers("P", 0).Single();
Assert.False(p.BaseType().IsErrorType());
Assert.Equal("N<P.Q>", p.BaseType().ToTestDisplayString());
}
[Fact]
public void EricLiCase8()
{
// should not be cyclic
var text =
@"
class N<T> {}
class R : N<R.S.T>{
public class S {
public class T {}
}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var r = global.GetTypeMembers("R", 0).Single();
var rBase = r.BaseType();
Assert.False(rBase.IsErrorType());
Assert.Equal("N<R.S.T>", rBase.ToTestDisplayString());
}
[Fact]
public void EricLiCase9()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
class U : U.I
{
public interface I {};
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var u = global.GetTypeMembers("U", 0).Single();
var ifaces = u.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("U.I", ifaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase10()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
interface IX : C.IY {}
class C : IX {
public interface IY {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single();
var ifaces = c.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("IX", ifaces[0].ToTestDisplayString());
var ix = ifaces[0];
var ixFaces = ix.Interfaces();
Assert.Equal(1, ixFaces.Length);
Assert.False(ixFaces[0].IsErrorType());
Assert.Equal("C.IY", ixFaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase11()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
class X : Y.I {}
class Y : X {
public interface I {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var ifaces = x.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("Y.I", ifaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase12()
{
// G should not be in scope
var text =
@"
class B : G {
public class G {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var b = global.GetTypeMembers("B", 0).Single();
Assert.True(b.BaseType().IsErrorType());
}
[Fact]
public void EricLiCase14()
{
// this should be cyclic
var text =
@"
class B {}
class D {}
class Z<T> : E<B> {}
class E<U> : Z<D> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var z = global.GetTypeMembers("Z", 1).Single();
Assert.True(z.BaseType().IsErrorType());
}
[Fact]
public void VladResCase01()
{
var text = @"
class A : A { }
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'A' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A"));
}
[Fact]
public void VladResCase02()
{
var text = @"
class A : B { }
class B : A { }
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'B' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B", "A"),
// (3,7): error CS0146: Circular base type dependency involving 'A' and 'B'
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "B"));
}
[Fact]
public void VladResCase03()
{
var text = @"
class A : A.B
{
public class B { }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'A.B' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A.B", "A"));
}
[Fact]
public void VladResCase04()
{
var text = @"
class A : A.I
{
public interface I { }
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase05()
{
var text = @"
class A : A.I
{
private interface I { }
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase06()
{
var text = @"
class A : A.B.I
{
private class B : A
{
public interface I { }
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase07()
{
var text = @"
class A : A.B.B.I
{
private class B : A
{
public interface I { }
}
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A.B"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "A.B"));
}
[Fact]
public void VladResCase08()
{
var text = @"
class A : C<A.B>
{
public class B
{
}
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase09()
{
var text = @"
class A : C<A.B.D>
{
public class B
{
public class D { }
}
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase10()
{
var text = @"
class A : C<A.B.B>
{
public class B : A { }
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A.B"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "A.B"));
}
[Fact]
public void VladResCase11()
{
var text = @"
class A : C<E>
{
public class B
{
public class D { }
}
}
class C<T> { }
class E : A.B.D { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase12()
{
var text = @"
class A : C<E.F>
{
public class B
{
public class D
{
public class F { }
}
}
}
class C<T> { }
class E : A.B.D { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase13()
{
var text = @"
class A<T>
{
public class B { }
}
class C : A<D.B> { }
class D : C { }
";
CreateCompilation(text).VerifyDiagnostics(
// (7,15): error CS0426: The type name 'B' does not exist in the type 'D'
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "D"));
}
[Fact]
public void VladResCase14()
{
var text = @"
class A<T>
{
public class B { }
}
class C : A<C>, I<C.B> { }
interface I<T> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (7,21): error CS0146: Circular base type dependency involving 'C' and 'C'
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("C", "C"));
}
[Fact]
public void VladResCase15()
{
var text = @"
class X
{
public interface Z { }
}
class A
{
public class X
{
public class V { }
}
}
class B : A, B.Y.Z
{
public class Y : X { }
public class C : B.Y.V { }
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "X").WithArguments("B", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Z").WithArguments("Z", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "V").WithArguments("V", "B.Y"));
}
[Fact]
public void VladResCase16()
{
var text = @"
class X
{
public interface Z { }
}
class A<T>
{
public class X
{
public class V { }
}
}
class B : A<B.Y.Z>
{
public class Y : X { }
public class C : B.Y.V { }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (15,17): error CS0146: Circular base type dependency involving 'B.Y' and 'B'
Diagnostic(ErrorCode.ERR_CircularBase, "X").WithArguments("B", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Z").WithArguments("Z", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "V").WithArguments("V", "B.Y"));
}
[Fact]
public void CyclicInterfaces3()
{
var C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1;
var C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2;
var text =
@"
interface I4 : I1 {}
";
var comp = CreateCompilation(text, new[] { C1, C2 });
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("I4", 0).Single();
var x_base_base = x.Interfaces().First().Interfaces().First() as ErrorTypeSymbol;
var er = x_base_base.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'I2' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted4()
{
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
var text =
@"
public class ClassB : ClassA {}
";
var comp = CreateCompilation(text, new[] { ClassAv1 }, assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.True(B1.IsFromCompilation(comp));
Assert.IsAssignableFrom<PENamedTypeSymbol>(B_base);
Assert.IsAssignableFrom<PENamedTypeSymbol>(A_base);
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[] { ClassAv2, new CSharpCompilationReference(comp) });
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsType<Retargeting.RetargetingNamedTypeSymbol>(B2);
Assert.Same(B1, ((Retargeting.RetargetingNamedTypeSymbol)B2).UnderlyingNamedType);
Assert.Same(C.BaseType(), B2);
Assert.False(B2.IsSerializable);
var errorBase = B2.BaseType() as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var errorBase1 = A2.BaseType() as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted5()
{
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
var ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule;
var text = @"// hi";
var comp = CreateCompilation(text, new[]
{
ClassAv1,
ClassBv1
},
assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Distinct().Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B1);
Assert.IsAssignableFrom<PENamedTypeSymbol>(B_base);
Assert.IsAssignableFrom<PENamedTypeSymbol>(A_base);
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv2,
new CSharpCompilationReference(comp)
});
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2);
Assert.NotEqual(B1, B2);
Assert.Same(((PEModuleSymbol)B1.ContainingModule).Module, ((PEModuleSymbol)B2.ContainingModule).Module);
Assert.Equal(((PENamedTypeSymbol)B1).Handle, ((PENamedTypeSymbol)B2).Handle);
Assert.Same(C.BaseType(), B2);
var errorBase = B2.BaseType() as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var errorBase1 = A2.BaseType() as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted6()
{
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
var text =
@"
public class ClassB : ClassA {}
";
var comp = CreateCompilation(text, new[] { ClassAv2 }, assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.True(B1.IsFromCompilation(comp));
var errorBase = B_base as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'ClassA' and 'ClassB'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var errorBase1 = A_base as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv1,
new CSharpCompilationReference(comp),
});
var global = comp2.GlobalNamespace;
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsType<Retargeting.RetargetingNamedTypeSymbol>(B2);
Assert.Same(B1, ((Retargeting.RetargetingNamedTypeSymbol)B2).UnderlyingNamedType);
Assert.Same(C.BaseType(), B2);
Assert.Same(B2.BaseType(), A2);
}
[Fact]
public void CyclicRetargeted7()
{
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
var ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule;
var text = @"// hi";
var comp = CreateCompilation(text, new MetadataReference[]
{
ClassAv2,
ClassBv1,
},
assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Distinct().Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B1);
var errorBase = B_base as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var errorBase1 = A_base as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv1,
new CSharpCompilationReference(comp)
});
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2);
Assert.NotEqual(B1, B2);
Assert.Same(((PEModuleSymbol)B1.ContainingModule).Module, ((PEModuleSymbol)B2.ContainingModule).Module);
Assert.Equal(((PENamedTypeSymbol)B1).Handle, ((PENamedTypeSymbol)B2).Handle);
Assert.Same(C.BaseType(), B2);
var A2 = global.GetTypeMembers("ClassA", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(A2.BaseType());
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2.BaseType());
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void NestedNames1(string ob, string cb)
{
var text =
@"
namespace N
" + ob + @"
static class C
{
class A<T>
{
class B<U> : A<B<U>>.D { }
private class D { }
}
}
" + cb + @"
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n = global.GetMembers("N").OfType<NamespaceSymbol>().Single();
var c = n.GetTypeMembers("C", 0).Single();
var a = c.GetTypeMembers("A", 1).Single();
var b = a.GetTypeMembers("B", 1).Single();
var d = a.GetTypeMembers("D", 0).Single();
Assert.Equal(Accessibility.Private, d.DeclaredAccessibility);
Assert.Equal(d.OriginalDefinition, b.BaseType().OriginalDefinition);
Assert.NotEqual(d, b.BaseType());
}
[Fact]
public void Using1()
{
var text =
@"
namespace N1 {
class A {}
}
namespace N2 {
using N1; // bring N1.A into scope
class B : A {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 0).Single();
var b = n2.GetTypeMembers("B", 0).Single();
Assert.Equal(a, b.BaseType());
}
[Fact]
public void Using2()
{
var text =
@"
namespace N1 {
class A<T> {}
}
namespace N2 {
using X = N1.A<B>; // bring N1.A into scope
class B : X {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 1).Single();
var b = n2.GetTypeMembers("B", 0).Single();
var bt = b.BaseType();
Assert.Equal(a, b.BaseType().OriginalDefinition);
Assert.Equal(b, (b.BaseType() as NamedTypeSymbol).TypeArguments()[0]);
}
[Fact]
public void Using3()
{
var text =
@"
using @global = N;
namespace N { class C {} }
class D : global::N.C {}";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var d = global.GetMembers("D").Single() as NamedTypeSymbol;
Assert.NotEqual(SymbolKind.ErrorType, d.BaseType().Kind);
}
[Fact]
public void Arrays1()
{
var text =
@"
class G<T> { }
class C : G<C[,][]>
{
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var g = global.GetTypeMembers("G", 1).Single();
var c = global.GetTypeMembers("C", 0).Single();
Assert.Equal(g, c.BaseType().OriginalDefinition);
var garg = c.BaseType().TypeArguments()[0];
Assert.Equal(SymbolKind.ArrayType, garg.Kind);
var carr1 = garg as ArrayTypeSymbol;
var carr2 = carr1.ElementType as ArrayTypeSymbol;
Assert.Equal(c, carr2.ElementType);
Assert.Equal(2, carr1.Rank);
Assert.Equal(1, carr2.Rank);
Assert.True(carr2.IsSZArray);
}
[Fact]
public void MultiSource()
{
var text1 =
@"
using N2;
namespace N1 {
class A {}
}
partial class X {
class B1 : B {}
}
partial class Broken {
class A2 : A {} // error: A not found
}
";
var text2 =
@"
using N1;
namespace N2 {
class B {}
}
partial class X {
class A1 : A {}
}
partial class Broken {
class B2 : B {} // error: B not found
}
";
var comp = CreateEmptyCompilation(new[] { text1, text2 });
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 0).Single();
var b = n2.GetTypeMembers("B", 0).Single();
var x = global.GetTypeMembers("X", 0).Single();
var a1 = x.GetTypeMembers("A1", 0).Single();
Assert.Equal(a, a1.BaseType());
var b1 = x.GetTypeMembers("B1", 0).Single();
Assert.Equal(b, b1.BaseType());
var broken = global.GetTypeMembers("Broken", 0).Single();
var a2 = broken.GetTypeMembers("A2", 0).Single();
Assert.NotEqual(a, a2.BaseType());
Assert.Equal(SymbolKind.ErrorType, a2.BaseType().Kind);
var b2 = broken.GetTypeMembers("B2", 0).Single();
Assert.NotEqual(b, b2.BaseType());
Assert.Equal(SymbolKind.ErrorType, b2.BaseType().Kind);
}
[Fact]
public void CyclicUsing1()
{
var text =
@"
using M = B.X;
using N = A.Y;
public class A : M { }
public class B : N { }
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var b = global.GetTypeMembers("B", 0).Single();
var abase = a.BaseType();
Assert.Equal(SymbolKind.ErrorType, abase.Kind);
var bbase = b.BaseType();
Assert.Equal(SymbolKind.ErrorType, bbase.Kind);
}
[Fact]
public void BaseError()
{
var text = "class C : Bar { }";
var tree = Parse(text);
var comp = CreateCompilation(tree);
Assert.Equal(1, comp.GetDeclarationDiagnostics().Count());
}
[Fact, WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
public void NamespaceClassInterfaceEscapedIdentifier1()
{
var text = @"
namespace @if
{
public interface @break { }
public class @int<@string> { }
public class @float : @int<@break>, @if.@break { }
}";
var comp = CreateCompilation(Parse(text));
NamespaceSymbol nif = (NamespaceSymbol)comp.SourceModule.GlobalNamespace.GetMembers("if").Single();
Assert.Equal("if", nif.Name);
Assert.Equal("@if", nif.ToString());
NamedTypeSymbol cfloat = (NamedTypeSymbol)nif.GetMembers("float").Single();
Assert.Equal("float", cfloat.Name);
Assert.Equal("@if.@float", cfloat.ToString());
NamedTypeSymbol cint = cfloat.BaseType();
Assert.Equal("int", cint.Name);
Assert.Equal("@if.@int<@if.@break>", cint.ToString());
NamedTypeSymbol ibreak = cfloat.Interfaces().Single();
Assert.Equal("break", ibreak.Name);
Assert.Equal("@if.@break", ibreak.ToString());
}
[Fact, WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
public void NamespaceClassInterfaceEscapedIdentifier2()
{
var text = @"
namespace @if
{
public interface @break { }
public class @int<@string> { }
public class @float : @int<@break> : @if.@break { }
}";
var comp = CreateCompilation(Parse(text));
NamespaceSymbol nif = (NamespaceSymbol)comp.SourceModule.GlobalNamespace.GetMembers("if").Single();
Assert.Equal("if", nif.Name);
Assert.Equal("@if", nif.ToString());
NamedTypeSymbol cfloat = (NamedTypeSymbol)nif.GetMembers("float").Single();
Assert.Equal("float", cfloat.Name);
Assert.Equal("@if.@float", cfloat.ToString());
NamedTypeSymbol cint = cfloat.BaseType();
Assert.Equal("int", cint.Name);
Assert.Equal("@if.@int<@if.@break>", cint.ToString());
// No interfaces as the above doesn't parse due to the errant : in the base list.
Assert.Empty(cfloat.Interfaces());
}
[WorkItem(539328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539328")]
[WorkItem(539789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539789")]
[Fact]
public void AccessInBaseClauseCheckedWithRespectToContainer()
{
var text = @"
class X
{
protected class A { }
}
class Y : X
{
private class C : X.A { }
private class B { }
}";
var comp = CreateCompilation(Parse(text));
var diags = comp.GetDeclarationDiagnostics();
Assert.Empty(diags);
}
/// <summary>
/// The base type of a nested type should not change depending on
/// whether or not the base type of the containing type has been
/// evaluated.
/// </summary>
[WorkItem(539744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539744")]
[Fact]
public void BaseTypeEvaluationOrder()
{
var text = @"
class A<T>
{
public class X { }
}
class B : A<B.Y.Error>
{
public class Y : X { }
}
";
//B.BaseType(), B.Y.BaseType
{
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("B")[0];
var classY = (NamedTypeSymbol)classB.GetMembers("Y")[0];
var baseB = classB.BaseType();
Assert.Equal("A<B.Y.Error>", baseB.ToTestDisplayString());
Assert.False(baseB.IsErrorType());
var baseY = classY.BaseType();
Assert.Equal("X", baseY.ToTestDisplayString());
Assert.True(baseY.IsErrorType());
}
//B.Y.BaseType(), B.BaseType
{
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("B")[0];
var classY = (NamedTypeSymbol)classB.GetMembers("Y")[0];
var baseY = classY.BaseType();
Assert.Equal("X", baseY.ToTestDisplayString());
Assert.True(baseY.IsErrorType());
var baseB = classB.BaseType();
Assert.Equal("A<B.Y.Error>", baseB.ToTestDisplayString());
Assert.False(baseB.IsErrorType());
}
}
[Fact]
public void BaseInterfacesInMetadata()
{
var text = @"
interface I1 { }
interface I2 : I1 { }
class C : I2 { }
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var baseInterface = global.GetMember<NamedTypeSymbol>("I1");
var derivedInterface = global.GetMember<NamedTypeSymbol>("I2");
var @class = global.GetMember<NamedTypeSymbol>("C");
var bothInterfaces = ImmutableArray.Create(baseInterface, derivedInterface);
Assert.Equal(baseInterface, derivedInterface.AllInterfaces().Single());
Assert.Equal(derivedInterface, @class.Interfaces().Single());
Assert.True(@class.AllInterfaces().SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var cciInterfaces = typeDef.Interfaces(context)
.Select(impl => impl.TypeRef.GetInternalSymbol()).Cast<NamedTypeSymbol>().AsImmutable();
Assert.True(cciInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
context.Diagnostics.Verify();
}
[Fact(), WorkItem(544454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544454")]
public void InterfaceImplementedWithPrivateType()
{
var textA = @"
using System;
using System.Collections;
using System.Collections.Generic;
public class A: IEnumerable<A.MyPrivateType>
{
private class MyPrivateType {}
IEnumerator<MyPrivateType> IEnumerable<A.MyPrivateType>.GetEnumerator()
{ throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator()
{ throw new NotImplementedException(); }
}";
var textB = @"
using System.Collections.Generic;
class Z
{
public IEnumerable<object> goo(A a)
{
return a;
}
}";
CSharpCompilation c1 = CreateCompilation(textA);
CSharpCompilation c2 = CreateCompilation(textB, new[] { new CSharpCompilationReference(c1) });
//Works this way, but doesn't when compilation is supplied as metadata
Assert.Equal(0, c1.GetDiagnostics().Count());
Assert.Equal(0, c2.GetDiagnostics().Count());
var metadata1 = c1.EmitToArray(options: new EmitOptions(metadataOnly: true));
c2 = CreateCompilation(textB, new[] { MetadataReference.CreateFromImage(metadata1) });
Assert.Equal(0, c2.GetDiagnostics().Count());
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[Fact()]
public void ProtectedInternalNestedBaseClass()
{
var source1 = @"
public class PublicClass
{
protected internal class ProtectedInternalClass
{
public ProtectedInternalClass()
{
}
}
}
";
var source2 = @"
class C : PublicClass.ProtectedInternalClass
{
}
";
var compilation1 = CreateCompilation(source1, assemblyName: "One");
compilation1.VerifyDiagnostics();
var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }, assemblyName: "Two");
compilation2.VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedInternalClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedInternalClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedInternalClass").WithArguments("PublicClass.ProtectedInternalClass").WithLocation(2, 23)
);
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void ProtectedAndInternalNestedBaseClass()
{
// Note: the problem was with the "protected" check so we use InternalsVisibleTo to make
// the "internal" check succeed.
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string)
= {string('Test')}
}
.class public auto ansi beforefieldinit PublicClass
extends [mscorlib]System.Object
{
.class auto ansi nested famandassem beforefieldinit ProtectedAndInternalClass
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class ProtectedAndInternalClass
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class PublicClass
";
var csharp = @"
class C : PublicClass.ProtectedAndInternalClass
{
}
";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false).VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedAndInternalClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedAndInternalClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedAndInternalClass").WithArguments("PublicClass.ProtectedAndInternalClass").WithLocation(2, 23)
);
}
[WorkItem(530144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530144")]
[Fact()]
public void UnifyingBaseInterfaces01()
{
var il = @"
.assembly extern mscorlib
{
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module a.dll
.class interface public abstract auto ansi J`1<T>
{
}
.class interface public abstract auto ansi I`1<T>
implements class J`1<int32>,
class J`1<!T>
{
}";
var csharp =
@"public class C
{
public static I<int> x;
static void F(I<int> x)
{
I<int> t = C.x;
}
}
public class D : I<int> {}
public interface I2 : I<int> {}";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false).VerifyDiagnostics(
// (4,26): error CS0648: 'I<int>' is a type not supported by the language
// static void F(I<int> x)
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<int>").WithLocation(4, 26),
// (3,26): error CS0648: 'I<int>' is a type not supported by the language
// public static I<int> x;
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<int>").WithLocation(3, 26),
// (10,14): error CS0648: 'I<int>' is a type not supported by the language
// public class D : I<int> {}
Diagnostic(ErrorCode.ERR_BogusType, "D").WithArguments("I<int>").WithLocation(10, 14),
// (11,18): error CS0648: 'I<int>' is a type not supported by the language
// public interface I2 : I<int> {}
Diagnostic(ErrorCode.ERR_BogusType, "I2").WithArguments("I<int>").WithLocation(11, 18),
// (6,9): error CS0648: 'I<int>' is a type not supported by the language
// I<int> t = C.x;
Diagnostic(ErrorCode.ERR_BogusType, "I<int>").WithArguments("I<int>").WithLocation(6, 9)
);
}
[WorkItem(530144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530144")]
[Fact()]
public void UnifyingBaseInterfaces02()
{
var il = @"
.assembly extern mscorlib
{
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module a.dll
.class interface public abstract auto ansi J`1<T>
{
}
.class interface public abstract auto ansi I`1<T>
implements class J`1<object>,
class J`1<!T>
{
}";
var csharp =
@"public class C
{
public static I<dynamic> x;
static void F(I<dynamic> x)
{
I<dynamic> t = C.x;
}
}";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false, targetFramework: TargetFramework.Standard).VerifyDiagnostics(
// (4,30): error CS0648: 'I<dynamic>' is a type not supported by the language
// static void F(I<dynamic> x)
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<dynamic>").WithLocation(4, 30),
// (3,30): error CS0648: 'I<dynamic>' is a type not supported by the language
// public static I<dynamic> x;
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<dynamic>").WithLocation(3, 30),
// (6,9): error CS0648: 'I<dynamic>' is a type not supported by the language
// I<dynamic> t = C.x;
Diagnostic(ErrorCode.ERR_BogusType, "I<dynamic>").WithArguments("I<dynamic>").WithLocation(6, 9)
);
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[Fact()]
public void ProtectedNestedBaseClass()
{
var source1 = @"
public class PublicClass
{
protected class ProtectedClass
{
public ProtectedClass()
{
}
}
}
";
var source2 = @"
class C : PublicClass.ProtectedClass
{
}
";
var compilation1 = CreateCompilation(source1, assemblyName: "One");
compilation1.VerifyDiagnostics();
var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }, assemblyName: "Two");
compilation2.VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedClass").WithArguments("PublicClass.ProtectedClass"));
}
[WorkItem(545589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545589")]
[Fact]
public void MissingTypeArgumentInBase()
{
var text =
@"interface I<out T> { }
class B : I<object>
{
public static void Goo<T>(I<T> x)
{
}
public static void Goo<T>() where T : I<>
{
}
static void Main()
{
Goo(new B());
}
}";
var comp = CreateCompilation(Parse(text));
comp.VerifyDiagnostics(
// (9,43): error CS7003: Unexpected use of an unbound generic name
// public static void Goo<T>() where T : I<>
Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "I<>")
);
}
[WorkItem(792711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792711")]
[Fact]
public void Repro792711()
{
var source = @"
public class Base<T>
{
}
public class Derived<T> : Base<Derived<T>>
{
}
";
var metadataRef = CreateCompilation(source).EmitToImageReference(embedInteropTypes: true);
var comp = CreateCompilation("", new[] { metadataRef });
var derived = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
Assert.Equal(TypeKind.Class, derived.TypeKind);
}
[WorkItem(872825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872825")]
[Fact]
public void InaccessibleStructInterface()
{
var source =
@"class C
{
protected interface I
{
}
}
struct S : C.I
{
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0122: 'C.I' is inaccessible due to its protection level
// struct S : C.I
Diagnostic(ErrorCode.ERR_BadAccess, "I").WithArguments("C.I").WithLocation(7, 14));
}
[WorkItem(872948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872948")]
[Fact]
public void MissingNestedMemberInStructImplementsClause()
{
var source =
@"struct S : S.I
{
}";
var compilation = CreateCompilation(source);
// Ideally report "CS0426: The type name 'I' does not exist in the type 'S'"
// instead. Bug #896959.
compilation.VerifyDiagnostics(
// (1,14): error CS0146: Circular base type dependency involving 'S' and 'S'
// struct S : S.I
Diagnostic(ErrorCode.ERR_CircularBase, "I").WithArguments("S", "S").WithLocation(1, 14));
}
[WorkItem(896959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896959")]
[Fact(Skip = "896959")]
public void MissingNestedMemberInClassImplementsClause()
{
var source =
@"class C : C.I
{
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (1,13): error CS0426: The type name 'I' does not exist in the type 'C'
// class C : C.I
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "I").WithArguments("I", "C").WithLocation(1, 13));
}
[Fact, WorkItem(1085632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085632")]
public void BaseLookupRecursionWithStaticImport01()
{
const string source =
@"using A<int>.B;
using D;
class A<T> : C
{
public static class B { }
}
class D
{
public class C { }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,14): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?)
// class A<T> : C
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C").WithLocation(4, 14),
// (1,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'A<int>.B' is a type not a namespace. Consider a 'using static' directive instead
// using A<int>.B;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "A<int>.B").WithArguments("A<int>.B").WithLocation(1, 7),
// (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'D' is a type not a namespace. Consider a 'using static' directive instead
// using D;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "D").WithArguments("D").WithLocation(2, 7),
// (2,1): hidden CS8019: Unnecessary using directive.
// using D;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using D;").WithLocation(2, 1),
// (1,1): hidden CS8019: Unnecessary using directive.
// using A<int>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A<int>.B;").WithLocation(1, 1)
);
}
[Fact, WorkItem(1085632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085632")]
public void BaseLookupRecursionWithStaticImport02()
{
const string source =
@"using static A<int>.B;
using static D;
class A<T> : C
{
public static class B { }
}
class D
{
public class C { }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using static A<int>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int>.B;").WithLocation(1, 1)
);
}
[Fact]
public void BindBases()
{
// Ensure good semantic model data even in error scenarios
var text =
@"
class B {
public B(long x) {}
}
class D : B {
extern D(int x) : base(y) {}
static int y;
}";
var comp = CreateCompilationWithMscorlib45(text);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var baseY = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "y").OfType<ExpressionSyntax>().First();
var typeInfo = model.GetTypeInfo(baseY);
Assert.Equal(SpecialType.System_Int32, typeInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_Int64, typeInfo.ConvertedType.SpecialType);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_01()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
CompileAndVerify(comp);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_02()
{
var text =
@"
using static CrashTest.Crash<object>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
class Class3
{
AbstractClass Test()
{
return null;
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,14): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// using static CrashTest.Crash<object>;
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "CrashTest.Crash<object>").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(2, 14),
// (6,11): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// class Class2 : AbstractClass
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Class2").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(6, 11),
// (21,23): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// AbstractClass Test()
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Test").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(21, 23)
);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_03()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
[System.Obsolete]
class Class2 : AbstractClass
{
}
[System.Obsolete]
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,30): warning CS0612: 'Class2' is obsolete
// using static CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CrashTest.Class2").WithArguments("CrashTest.Class2").WithLocation(2, 30),
// (2,14): warning CS0612: 'Crash<Class2>' is obsolete
// using static CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CrashTest.Crash<CrashTest.Class2>").WithArguments("CrashTest.Crash<CrashTest.Class2>").WithLocation(2, 14));
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_04()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
[System.Obsolete]
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (11,18): warning CS0612: 'Crash<T>.AbstractClass' is obsolete
// where T: Crash<T>.AbstractClass
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Crash<T>.AbstractClass").WithArguments("CrashTest.Crash<T>.AbstractClass").WithLocation(11, 18),
// (6,20): warning CS0612: 'Crash<Class2>.AbstractClass' is obsolete
// class Class2 : AbstractClass
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "AbstractClass").WithArguments("CrashTest.Crash<CrashTest.Class2>.AbstractClass").WithLocation(6, 20)
);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_05()
{
var text =
@"
using CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'Crash<Class2>' is a type not a namespace. Consider a 'using static' directive instead
// using CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "CrashTest.Crash<CrashTest.Class2>").WithArguments("CrashTest.Crash<CrashTest.Class2>").WithLocation(2, 7),
// (6,20): error CS0246: The type or namespace name 'AbstractClass' could not be found (are you missing a using directive or an assembly reference?)
// class Class2 : AbstractClass
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "AbstractClass").WithArguments("AbstractClass").WithLocation(6, 20),
// (2,1): hidden CS8019: Unnecessary using directive.
// using CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using CrashTest.Crash<CrashTest.Class2>;").WithLocation(2, 1)
);
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CycleTypeArgument()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C>.B { }
class F : A<D>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17));
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CycleArray()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C[]>.B { }
class F : A<D[]>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17));
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CyclePointer()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C*>.B { }
class F : A<D*>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17),
// (13,11): error CS0306: The type 'Base.D*' may not be used as a type argument
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("Base.D*").WithLocation(13, 11),
// (13,11): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Base.D')
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "F").WithArguments("Base.D").WithLocation(13, 11),
// (12,11): error CS0306: The type 'Base.C*' may not be used as a type argument
// class E : A<C*>.B { }
Diagnostic(ErrorCode.ERR_BadTypeArgument, "E").WithArguments("Base.C*").WithLocation(12, 11),
// (12,11): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Base.C')
// class E : A<C*>.B { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "E").WithArguments("Base.C").WithLocation(12, 11));
}
[Fact]
[WorkItem(1107185, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107185")]
public void Tuple_MissingNestedTypeArgument_01()
{
var source =
@"interface I<T>
{
}
class A : I<(object, A.B)>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,24): error CS0146: Circular base type dependency involving 'A' and 'A'
// class A : I<(object, A.B)>
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "A").WithLocation(4, 24));
}
[Fact]
[WorkItem(1107185, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107185")]
public void Tuple_MissingNestedTypeArgument_02()
{
var source =
@"class A<T>
{
}
class B : A<(object, B.C)>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,24): error CS0146: Circular base type dependency involving 'B' and 'B'
// class B : A<(object, B.C)>
Diagnostic(ErrorCode.ERR_CircularBase, "C").WithArguments("B", "B").WithLocation(4, 24));
}
[Fact]
public void Tuple_MissingNestedTypeArgument_03()
{
var source =
@"interface I<T>
{
}
class A : I<System.ValueTuple<object, A.B>>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,41): error CS0146: Circular base type dependency involving 'A' and 'A'
// class A : I<System.ValueTuple<object, A.B>>
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "A").WithLocation(4, 41));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Retargeting = Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class BaseClassTests : CSharpTestBase
{
[Fact]
public void CyclicBases1()
{
var text =
@"
class X : Y {}
class Y : X {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var y = global.GetTypeMembers("Y", 0).Single();
Assert.NotEqual(y, x.BaseType());
Assert.NotEqual(x, y.BaseType());
Assert.Equal(SymbolKind.ErrorType, x.BaseType().Kind);
Assert.Equal(SymbolKind.ErrorType, y.BaseType().Kind);
Assert.Equal("Y", x.BaseType().Name);
Assert.Equal("X", y.BaseType().Name);
}
[Fact]
public void CyclicBases2()
{
var text =
@"
class X : Y.n {}
class Y : X.n {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var y = global.GetTypeMembers("Y", 0).Single();
Assert.NotEqual(y, x.BaseType());
Assert.NotEqual(x, y.BaseType());
Assert.Equal(SymbolKind.ErrorType, x.BaseType().Kind);
Assert.Equal(SymbolKind.ErrorType, y.BaseType().Kind);
Assert.Equal("n", x.BaseType().Name);
Assert.Equal("n", y.BaseType().Name);
}
[Fact]
public void CyclicBases3()
{
var C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1;
var C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2;
var text =
@"
class C4 : C1 {}
";
var comp = CreateCompilation(text, new[] { C1, C2 });
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("C4", 0).Single();
var x_base_base = x.BaseType().BaseType() as ErrorTypeSymbol;
var er = x_base_base.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'C2' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(538506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538506")]
[Fact]
public void CyclicBasesRegress4140()
{
var text =
@"
class A<T>
{
class B : A<E> { }
class E : B.E { }
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 1).Single();
var b = a.GetTypeMembers("B", 0).Single();
var e = a.GetTypeMembers("E", 0).Single();
Assert.NotEqual(e, e.BaseType());
var x_base = e.BaseType() as ErrorTypeSymbol;
var er = x_base.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'A<A<T>.E>.E' and 'A<T>.E'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(538526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538526")]
[Fact]
public void CyclicBasesRegress4166()
{
var text =
@"
class A<T> {
public class C : B.D { }
}
class B {
public class D : A<int>.C { }
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 1).Single();
var b = global.GetTypeMembers("B", 0).Single();
var d = b.GetTypeMembers("D", 0).Single();
Assert.NotEqual(d, d.BaseType());
var x_base = d.BaseType() as ErrorTypeSymbol;
var er = x_base.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'A<int>.C' and 'B.D'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[WorkItem(4169, "DevDiv_Projects/Roslyn")]
[Fact]
public void CyclicBasesRegress4169()
{
var text =
@"
class A : object, A.IC
{
protected interface IC { }
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var ic = a.GetTypeMembers("IC", 0).Single();
Assert.Equal(a.Interfaces()[0], ic);
var diagnostics = comp.GetDeclarationDiagnostics();
Assert.Equal(0, diagnostics.Count());
}
[WorkItem(527551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527551")]
[Fact]
public void CyclicBasesRegress4168()
{
var text =
@"
class A : object, A.B.B.IC
{
public class B : A {
public interface IC { }
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var b = a.GetTypeMembers("B", 0).Single();
var ic = b.GetTypeMembers("IC", 0).Single();
Assert.NotEqual(b, b.BaseType());
Assert.NotEqual(a, b.BaseType());
Assert.Equal(SymbolKind.ErrorType, a.Interfaces()[0].Kind);
Assert.NotEqual(ic, a.Interfaces()[0]);
var diagnostics = comp.GetDeclarationDiagnostics();
Assert.Equal(2, diagnostics.Count());
}
[Fact]
public void CyclicBases4()
{
var text =
@"
class A<T> : B<A<T>> { }
class B<T> : A<B<T>> {
A<T> F() { return null; }
}
";
var comp = CreateCompilation(text);
comp.GetDeclarationDiagnostics().Verify(
// (2,7): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>'
// class A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>"),
// (3,7): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>'
// class B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>")
);
}
[Fact]
public void CyclicBases5()
{
// bases are cyclic, but you can still find members when binding bases
var text =
@"
class A : B {
public class X { }
}
class B : A {
public class Y { }
}
class Z : A.Y { }
class W : B.X { }
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var z = global.GetTypeMembers("Z", 0).Single();
var w = global.GetTypeMembers("W", 0).Single();
var zBase = z.BaseType();
Assert.Equal("Y", zBase.Name);
var wBase = w.BaseType();
Assert.Equal("X", wBase.Name);
}
[Fact]
public void CyclicBases6()
{
// bases are cyclic, but you can still search for members w/o infinite looping in binder
var text =
@"
class A : B {
public class X {}
}
class B : C {
public class Y {}
}
class C : A {
public class Z {}
}
";
var comp = (Compilation)CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
//var aBase = a.BaseType();
//Assert.True(aBase.IsErrorType());
//Assert.Equal("B", aBase.Name);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var classA = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
var someMemberInA = classA.Members[0];
int positionInA = someMemberInA.SpanStart;
var members = model.LookupSymbols(positionInA, a, "Z");
Assert.Equal(1, members.Length);
Assert.False(((ITypeSymbol)members[0]).IsErrorType());
Assert.Equal("C.Z", members[0].ToTestDisplayString());
var members2 = model.LookupSymbols(positionInA, a, "Q");
Assert.Equal(0, members2.Length);
}
[Fact]
public void CyclicBases7()
{
// bases are cyclic, but you can still search for members w/o infinite looping in binder
var text =
@"
class A : B<A.Y> {
public class X {}
}
class B<T> : A {
public class Y {}
}
";
var comp = (Compilation)CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
//var aBase = a.BaseType();
//Assert.True(aBase.IsErrorType());
//Assert.Equal("B", aBase.Name);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var classA = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
var someMemberInA = classA.Members[0];
int positionInA = someMemberInA.SpanStart;
var members = model.LookupSymbols(positionInA, a, "Q");
Assert.Equal(0, members.Length);
}
[Fact]
public void CyclicBases8()
{
var text = @"
public class A
{
protected class B
{
protected class C
{
public class X { }
}
}
}
internal class F : A
{
private class D : B
{
public class E : C.X { }
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (16,22): error CS0060: Inconsistent accessibility: base type 'A.B.C.X' is less accessible than class 'F.D.E'
// public class E : C.X { }
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "E").WithArguments("F.D.E", "A.B.C.X")
);
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void BadVisibilityPartial()
{
var text = @"
internal class NV
{
}
public partial class C1
{
}
partial class C1 : NV
{
}
public partial class C1
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (10,15): error CS0060: Inconsistent accessibility: base type 'NV' is less accessible than class 'C1'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 15));
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void StaticBasePartial()
{
var text = @"
static class NV
{
}
public partial class C1
{
}
partial class C1 : NV
{
}
public partial class C1
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (10,15): error CS0709: 'C1': cannot derive from static class 'NV'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_StaticBaseClass, "C1").WithArguments("NV", "C1").WithLocation(10, 15),
// (10,15): error CS0060: Inconsistent accessibility: base type 'NV' is less accessible than class 'C1'
// partial class C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 15));
}
[Fact, WorkItem(7878, "https://github.com/dotnet/roslyn/issues/7878")]
public void BadVisInterfacePartial()
{
var text = @"
interface IGoo
{
void Moo();
}
interface IBaz
{
void Noo();
}
interface IBam
{
void Zoo();
}
public partial interface IBar
{
}
partial interface IBar : IGoo, IBam
{
}
partial interface IBar : IBaz, IBaz
{
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (25,32): error CS0528: 'IBaz' is already listed in interface list
// partial interface IBar : IBaz, IBaz
Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "IBaz").WithArguments("IBaz").WithLocation(25, 32),
// (21,19): error CS0061: Inconsistent accessibility: base interface 'IGoo' is less accessible than interface 'IBar'
// partial interface IBar : IGoo, IBam
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IGoo").WithLocation(21, 19),
// (21,19): error CS0061: Inconsistent accessibility: base interface 'IBam' is less accessible than interface 'IBar'
// partial interface IBar : IGoo, IBam
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IBam").WithLocation(21, 19),
// (25,19): error CS0061: Inconsistent accessibility: base interface 'IBaz' is less accessible than interface 'IBar'
// partial interface IBar : IBaz, IBaz
Diagnostic(ErrorCode.ERR_BadVisBaseInterface, "IBar").WithArguments("IBar", "IBaz").WithLocation(25, 19));
}
[Fact]
public void EricLiCase1()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class A {
public class B {}
}
class C : A, I<C.B> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single();
var cBase = c.BaseType();
Assert.False(cBase.IsErrorType());
Assert.Equal("A", cBase.Name);
Assert.True(c.Interfaces().Single().TypeArguments().Single().IsErrorType()); //can't see base of C while evaluating C.B
}
[Fact]
public void EricLiCase2()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class E : I<E> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var e = global.GetTypeMembers("E", 0).Single();
Assert.Equal(1, e.Interfaces().Length);
Assert.Equal("I<E>", e.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase3()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class G : I<G.H> {
public class H {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var g = global.GetTypeMembers("G", 0).Single();
Assert.Equal(1, g.Interfaces().Length);
Assert.Equal("I<G.H>", g.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase4()
{
// should not be cyclic
var text =
@"
interface I<T> {}
class J : I<J.K.L> {
public class K {
public class L {}
}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var j = global.GetTypeMembers("J", 0).Single();
Assert.Equal(1, j.Interfaces().Length);
Assert.Equal("I<J.K.L>", j.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase5()
{
// should be cyclic
var text =
@"class M : M {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var m = global.GetTypeMembers("M", 0).Single();
Assert.True(m.BaseType().IsErrorType());
}
[Fact]
public void EricLiCase6()
{
// should not be cyclic
var text =
@"
class N<T> {}
class O : N<O> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var o = global.GetTypeMembers("O", 0).Single();
Assert.False(o.BaseType().IsErrorType());
Assert.Equal("N<O>", o.BaseType().ToTestDisplayString());
}
[Fact]
public void EricLiCase7()
{
// should not be cyclic
var text =
@"
class N<T> {}
class P : N<P.Q> {
public class Q {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var p = global.GetTypeMembers("P", 0).Single();
Assert.False(p.BaseType().IsErrorType());
Assert.Equal("N<P.Q>", p.BaseType().ToTestDisplayString());
}
[Fact]
public void EricLiCase8()
{
// should not be cyclic
var text =
@"
class N<T> {}
class R : N<R.S.T>{
public class S {
public class T {}
}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var r = global.GetTypeMembers("R", 0).Single();
var rBase = r.BaseType();
Assert.False(rBase.IsErrorType());
Assert.Equal("N<R.S.T>", rBase.ToTestDisplayString());
}
[Fact]
public void EricLiCase9()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
class U : U.I
{
public interface I {};
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var u = global.GetTypeMembers("U", 0).Single();
var ifaces = u.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("U.I", ifaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase10()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
interface IX : C.IY {}
class C : IX {
public interface IY {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single();
var ifaces = c.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("IX", ifaces[0].ToTestDisplayString());
var ix = ifaces[0];
var ixFaces = ix.Interfaces();
Assert.Equal(1, ixFaces.Length);
Assert.False(ixFaces[0].IsErrorType());
Assert.Equal("C.IY", ixFaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase11()
{
// should not be cyclic, legal to implement an inner interface
var text =
@"
class X : Y.I {}
class Y : X {
public interface I {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("X", 0).Single();
var ifaces = x.Interfaces();
Assert.Equal(1, ifaces.Length);
Assert.False(ifaces[0].IsErrorType());
Assert.Equal("Y.I", ifaces[0].ToTestDisplayString());
}
[Fact]
public void EricLiCase12()
{
// G should not be in scope
var text =
@"
class B : G {
public class G {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var b = global.GetTypeMembers("B", 0).Single();
Assert.True(b.BaseType().IsErrorType());
}
[Fact]
public void EricLiCase14()
{
// this should be cyclic
var text =
@"
class B {}
class D {}
class Z<T> : E<B> {}
class E<U> : Z<D> {}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var z = global.GetTypeMembers("Z", 1).Single();
Assert.True(z.BaseType().IsErrorType());
}
[Fact]
public void VladResCase01()
{
var text = @"
class A : A { }
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'A' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A"));
}
[Fact]
public void VladResCase02()
{
var text = @"
class A : B { }
class B : A { }
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'B' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B", "A"),
// (3,7): error CS0146: Circular base type dependency involving 'A' and 'B'
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "B"));
}
[Fact]
public void VladResCase03()
{
var text = @"
class A : A.B
{
public class B { }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (2,7): error CS0146: Circular base type dependency involving 'A.B' and 'A'
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A.B", "A"));
}
[Fact]
public void VladResCase04()
{
var text = @"
class A : A.I
{
public interface I { }
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase05()
{
var text = @"
class A : A.I
{
private interface I { }
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase06()
{
var text = @"
class A : A.B.I
{
private class B : A
{
public interface I { }
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase07()
{
var text = @"
class A : A.B.B.I
{
private class B : A
{
public interface I { }
}
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A.B"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "A.B"));
}
[Fact]
public void VladResCase08()
{
var text = @"
class A : C<A.B>
{
public class B
{
}
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase09()
{
var text = @"
class A : C<A.B.D>
{
public class B
{
public class D { }
}
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase10()
{
var text = @"
class A : C<A.B.B>
{
public class B : A { }
}
class C<T> { }
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("A", "A.B"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "A.B"));
}
[Fact]
public void VladResCase11()
{
var text = @"
class A : C<E>
{
public class B
{
public class D { }
}
}
class C<T> { }
class E : A.B.D { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase12()
{
var text = @"
class A : C<E.F>
{
public class B
{
public class D
{
public class F { }
}
}
}
class C<T> { }
class E : A.B.D { }
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void VladResCase13()
{
var text = @"
class A<T>
{
public class B { }
}
class C : A<D.B> { }
class D : C { }
";
CreateCompilation(text).VerifyDiagnostics(
// (7,15): error CS0426: The type name 'B' does not exist in the type 'D'
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "B").WithArguments("B", "D"));
}
[Fact]
public void VladResCase14()
{
var text = @"
class A<T>
{
public class B { }
}
class C : A<C>, I<C.B> { }
interface I<T> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (7,21): error CS0146: Circular base type dependency involving 'C' and 'C'
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("C", "C"));
}
[Fact]
public void VladResCase15()
{
var text = @"
class X
{
public interface Z { }
}
class A
{
public class X
{
public class V { }
}
}
class B : A, B.Y.Z
{
public class Y : X { }
public class C : B.Y.V { }
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_CircularBase, "X").WithArguments("B", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Z").WithArguments("Z", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "V").WithArguments("V", "B.Y"));
}
[Fact]
public void VladResCase16()
{
var text = @"
class X
{
public interface Z { }
}
class A<T>
{
public class X
{
public class V { }
}
}
class B : A<B.Y.Z>
{
public class Y : X { }
public class C : B.Y.V { }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (15,17): error CS0146: Circular base type dependency involving 'B.Y' and 'B'
Diagnostic(ErrorCode.ERR_CircularBase, "X").WithArguments("B", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Z").WithArguments("Z", "B.Y"),
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "V").WithArguments("V", "B.Y"));
}
[Fact]
public void CyclicInterfaces3()
{
var C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1;
var C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2;
var text =
@"
interface I4 : I1 {}
";
var comp = CreateCompilation(text, new[] { C1, C2 });
var global = comp.GlobalNamespace;
var x = global.GetTypeMembers("I4", 0).Single();
var x_base_base = x.Interfaces().First().Interfaces().First() as ErrorTypeSymbol;
var er = x_base_base.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'I2' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted4()
{
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
var text =
@"
public class ClassB : ClassA {}
";
var comp = CreateCompilation(text, new[] { ClassAv1 }, assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.True(B1.IsFromCompilation(comp));
Assert.IsAssignableFrom<PENamedTypeSymbol>(B_base);
Assert.IsAssignableFrom<PENamedTypeSymbol>(A_base);
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[] { ClassAv2, new CSharpCompilationReference(comp) });
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsType<Retargeting.RetargetingNamedTypeSymbol>(B2);
Assert.Same(B1, ((Retargeting.RetargetingNamedTypeSymbol)B2).UnderlyingNamedType);
Assert.Same(C.BaseType(), B2);
Assert.False(B2.IsSerializable);
var errorBase = B2.BaseType() as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var errorBase1 = A2.BaseType() as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted5()
{
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
var ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule;
var text = @"// hi";
var comp = CreateCompilation(text, new[]
{
ClassAv1,
ClassBv1
},
assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Distinct().Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B1);
Assert.IsAssignableFrom<PENamedTypeSymbol>(B_base);
Assert.IsAssignableFrom<PENamedTypeSymbol>(A_base);
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv2,
new CSharpCompilationReference(comp)
});
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2);
Assert.NotEqual(B1, B2);
Assert.Same(((PEModuleSymbol)B1.ContainingModule).Module, ((PEModuleSymbol)B2.ContainingModule).Module);
Assert.Equal(((PENamedTypeSymbol)B1).Handle, ((PENamedTypeSymbol)B2).Handle);
Assert.Same(C.BaseType(), B2);
var errorBase = B2.BaseType() as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var errorBase1 = A2.BaseType() as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void CyclicRetargeted6()
{
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
var text =
@"
public class ClassB : ClassA {}
";
var comp = CreateCompilation(text, new[] { ClassAv2 }, assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.True(B1.IsFromCompilation(comp));
var errorBase = B_base as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0146: Circular base type dependency involving 'ClassA' and 'ClassB'",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var errorBase1 = A_base as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv1,
new CSharpCompilationReference(comp),
});
var global = comp2.GlobalNamespace;
var A2 = global.GetTypeMembers("ClassA", 0).Single();
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsType<Retargeting.RetargetingNamedTypeSymbol>(B2);
Assert.Same(B1, ((Retargeting.RetargetingNamedTypeSymbol)B2).UnderlyingNamedType);
Assert.Same(C.BaseType(), B2);
Assert.Same(B2.BaseType(), A2);
}
[Fact]
public void CyclicRetargeted7()
{
var ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll;
var ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule;
var text = @"// hi";
var comp = CreateCompilation(text, new MetadataReference[]
{
ClassAv2,
ClassBv1,
},
assemblyName: "ClassB");
var global1 = comp.GlobalNamespace;
var B1 = global1.GetTypeMembers("ClassB", 0).Distinct().Single();
var A1 = global1.GetTypeMembers("ClassA", 0).Single();
var B_base = B1.BaseType();
var A_base = A1.BaseType();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B1);
var errorBase = B_base as ErrorTypeSymbol;
var er = errorBase.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassA' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var errorBase1 = A_base as ErrorTypeSymbol;
er = errorBase1.ErrorInfo;
Assert.Equal("error CS0268: Imported type 'ClassB' is invalid. It contains a circular base type dependency.",
er.ToString(EnsureEnglishUICulture.PreferredOrNull));
var ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll;
text =
@"
public class ClassC : ClassB {}
";
var comp2 = CreateCompilation(text, new MetadataReference[]
{
ClassAv1,
new CSharpCompilationReference(comp)
});
var global = comp2.GlobalNamespace;
var B2 = global.GetTypeMembers("ClassB", 0).Single();
var C = global.GetTypeMembers("ClassC", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2);
Assert.NotEqual(B1, B2);
Assert.Same(((PEModuleSymbol)B1.ContainingModule).Module, ((PEModuleSymbol)B2.ContainingModule).Module);
Assert.Equal(((PENamedTypeSymbol)B1).Handle, ((PENamedTypeSymbol)B2).Handle);
Assert.Same(C.BaseType(), B2);
var A2 = global.GetTypeMembers("ClassA", 0).Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(A2.BaseType());
Assert.IsAssignableFrom<PENamedTypeSymbol>(B2.BaseType());
}
[Theory, MemberData(nameof(FileScopedOrBracedNamespace))]
public void NestedNames1(string ob, string cb)
{
var text =
@"
namespace N
" + ob + @"
static class C
{
class A<T>
{
class B<U> : A<B<U>>.D { }
private class D { }
}
}
" + cb + @"
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n = global.GetMembers("N").OfType<NamespaceSymbol>().Single();
var c = n.GetTypeMembers("C", 0).Single();
var a = c.GetTypeMembers("A", 1).Single();
var b = a.GetTypeMembers("B", 1).Single();
var d = a.GetTypeMembers("D", 0).Single();
Assert.Equal(Accessibility.Private, d.DeclaredAccessibility);
Assert.Equal(d.OriginalDefinition, b.BaseType().OriginalDefinition);
Assert.NotEqual(d, b.BaseType());
}
[Fact]
public void Using1()
{
var text =
@"
namespace N1 {
class A {}
}
namespace N2 {
using N1; // bring N1.A into scope
class B : A {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 0).Single();
var b = n2.GetTypeMembers("B", 0).Single();
Assert.Equal(a, b.BaseType());
}
[Fact]
public void Using2()
{
var text =
@"
namespace N1 {
class A<T> {}
}
namespace N2 {
using X = N1.A<B>; // bring N1.A into scope
class B : X {}
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 1).Single();
var b = n2.GetTypeMembers("B", 0).Single();
var bt = b.BaseType();
Assert.Equal(a, b.BaseType().OriginalDefinition);
Assert.Equal(b, (b.BaseType() as NamedTypeSymbol).TypeArguments()[0]);
}
[Fact]
public void Using3()
{
var text =
@"
using @global = N;
namespace N { class C {} }
class D : global::N.C {}";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var d = global.GetMembers("D").Single() as NamedTypeSymbol;
Assert.NotEqual(SymbolKind.ErrorType, d.BaseType().Kind);
}
[Fact]
public void Arrays1()
{
var text =
@"
class G<T> { }
class C : G<C[,][]>
{
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var g = global.GetTypeMembers("G", 1).Single();
var c = global.GetTypeMembers("C", 0).Single();
Assert.Equal(g, c.BaseType().OriginalDefinition);
var garg = c.BaseType().TypeArguments()[0];
Assert.Equal(SymbolKind.ArrayType, garg.Kind);
var carr1 = garg as ArrayTypeSymbol;
var carr2 = carr1.ElementType as ArrayTypeSymbol;
Assert.Equal(c, carr2.ElementType);
Assert.Equal(2, carr1.Rank);
Assert.Equal(1, carr2.Rank);
Assert.True(carr2.IsSZArray);
}
[Fact]
public void MultiSource()
{
var text1 =
@"
using N2;
namespace N1 {
class A {}
}
partial class X {
class B1 : B {}
}
partial class Broken {
class A2 : A {} // error: A not found
}
";
var text2 =
@"
using N1;
namespace N2 {
class B {}
}
partial class X {
class A1 : A {}
}
partial class Broken {
class B2 : B {} // error: B not found
}
";
var comp = CreateEmptyCompilation(new[] { text1, text2 });
var global = comp.GlobalNamespace;
var n1 = global.GetMembers("N1").Single() as NamespaceSymbol;
var n2 = global.GetMembers("N2").Single() as NamespaceSymbol;
var a = n1.GetTypeMembers("A", 0).Single();
var b = n2.GetTypeMembers("B", 0).Single();
var x = global.GetTypeMembers("X", 0).Single();
var a1 = x.GetTypeMembers("A1", 0).Single();
Assert.Equal(a, a1.BaseType());
var b1 = x.GetTypeMembers("B1", 0).Single();
Assert.Equal(b, b1.BaseType());
var broken = global.GetTypeMembers("Broken", 0).Single();
var a2 = broken.GetTypeMembers("A2", 0).Single();
Assert.NotEqual(a, a2.BaseType());
Assert.Equal(SymbolKind.ErrorType, a2.BaseType().Kind);
var b2 = broken.GetTypeMembers("B2", 0).Single();
Assert.NotEqual(b, b2.BaseType());
Assert.Equal(SymbolKind.ErrorType, b2.BaseType().Kind);
}
[Fact]
public void CyclicUsing1()
{
var text =
@"
using M = B.X;
using N = A.Y;
public class A : M { }
public class B : N { }
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var b = global.GetTypeMembers("B", 0).Single();
var abase = a.BaseType();
Assert.Equal(SymbolKind.ErrorType, abase.Kind);
var bbase = b.BaseType();
Assert.Equal(SymbolKind.ErrorType, bbase.Kind);
}
[Fact]
public void BaseError()
{
var text = "class C : Bar { }";
var tree = Parse(text);
var comp = CreateCompilation(tree);
Assert.Equal(1, comp.GetDeclarationDiagnostics().Count());
}
[Fact, WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
public void NamespaceClassInterfaceEscapedIdentifier1()
{
var text = @"
namespace @if
{
public interface @break { }
public class @int<@string> { }
public class @float : @int<@break>, @if.@break { }
}";
var comp = CreateCompilation(Parse(text));
NamespaceSymbol nif = (NamespaceSymbol)comp.SourceModule.GlobalNamespace.GetMembers("if").Single();
Assert.Equal("if", nif.Name);
Assert.Equal("@if", nif.ToString());
NamedTypeSymbol cfloat = (NamedTypeSymbol)nif.GetMembers("float").Single();
Assert.Equal("float", cfloat.Name);
Assert.Equal("@if.@float", cfloat.ToString());
NamedTypeSymbol cint = cfloat.BaseType();
Assert.Equal("int", cint.Name);
Assert.Equal("@if.@int<@if.@break>", cint.ToString());
NamedTypeSymbol ibreak = cfloat.Interfaces().Single();
Assert.Equal("break", ibreak.Name);
Assert.Equal("@if.@break", ibreak.ToString());
}
[Fact, WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
public void NamespaceClassInterfaceEscapedIdentifier2()
{
var text = @"
namespace @if
{
public interface @break { }
public class @int<@string> { }
public class @float : @int<@break> : @if.@break { }
}";
var comp = CreateCompilation(Parse(text));
NamespaceSymbol nif = (NamespaceSymbol)comp.SourceModule.GlobalNamespace.GetMembers("if").Single();
Assert.Equal("if", nif.Name);
Assert.Equal("@if", nif.ToString());
NamedTypeSymbol cfloat = (NamedTypeSymbol)nif.GetMembers("float").Single();
Assert.Equal("float", cfloat.Name);
Assert.Equal("@if.@float", cfloat.ToString());
NamedTypeSymbol cint = cfloat.BaseType();
Assert.Equal("int", cint.Name);
Assert.Equal("@if.@int<@if.@break>", cint.ToString());
// No interfaces as the above doesn't parse due to the errant : in the base list.
Assert.Empty(cfloat.Interfaces());
}
[WorkItem(539328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539328")]
[WorkItem(539789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539789")]
[Fact]
public void AccessInBaseClauseCheckedWithRespectToContainer()
{
var text = @"
class X
{
protected class A { }
}
class Y : X
{
private class C : X.A { }
private class B { }
}";
var comp = CreateCompilation(Parse(text));
var diags = comp.GetDeclarationDiagnostics();
Assert.Empty(diags);
}
/// <summary>
/// The base type of a nested type should not change depending on
/// whether or not the base type of the containing type has been
/// evaluated.
/// </summary>
[WorkItem(539744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539744")]
[Fact]
public void BaseTypeEvaluationOrder()
{
var text = @"
class A<T>
{
public class X { }
}
class B : A<B.Y.Error>
{
public class Y : X { }
}
";
//B.BaseType(), B.Y.BaseType
{
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("B")[0];
var classY = (NamedTypeSymbol)classB.GetMembers("Y")[0];
var baseB = classB.BaseType();
Assert.Equal("A<B.Y.Error>", baseB.ToTestDisplayString());
Assert.False(baseB.IsErrorType());
var baseY = classY.BaseType();
Assert.Equal("X", baseY.ToTestDisplayString());
Assert.True(baseY.IsErrorType());
}
//B.Y.BaseType(), B.BaseType
{
var comp = CreateCompilation(text);
var classB = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("B")[0];
var classY = (NamedTypeSymbol)classB.GetMembers("Y")[0];
var baseY = classY.BaseType();
Assert.Equal("X", baseY.ToTestDisplayString());
Assert.True(baseY.IsErrorType());
var baseB = classB.BaseType();
Assert.Equal("A<B.Y.Error>", baseB.ToTestDisplayString());
Assert.False(baseB.IsErrorType());
}
}
[Fact]
public void BaseInterfacesInMetadata()
{
var text = @"
interface I1 { }
interface I2 : I1 { }
class C : I2 { }
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var baseInterface = global.GetMember<NamedTypeSymbol>("I1");
var derivedInterface = global.GetMember<NamedTypeSymbol>("I2");
var @class = global.GetMember<NamedTypeSymbol>("C");
var bothInterfaces = ImmutableArray.Create(baseInterface, derivedInterface);
Assert.Equal(baseInterface, derivedInterface.AllInterfaces().Single());
Assert.Equal(derivedInterface, @class.Interfaces().Single());
Assert.True(@class.AllInterfaces().SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
var typeDef = (Cci.ITypeDefinition)@class.GetCciAdapter();
var module = new PEAssemblyBuilder((SourceAssemblySymbol)@class.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var cciInterfaces = typeDef.Interfaces(context)
.Select(impl => impl.TypeRef.GetInternalSymbol()).Cast<NamedTypeSymbol>().AsImmutable();
Assert.True(cciInterfaces.SetEquals(bothInterfaces, EqualityComparer<NamedTypeSymbol>.Default));
context.Diagnostics.Verify();
}
[Fact(), WorkItem(544454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544454")]
public void InterfaceImplementedWithPrivateType()
{
var textA = @"
using System;
using System.Collections;
using System.Collections.Generic;
public class A: IEnumerable<A.MyPrivateType>
{
private class MyPrivateType {}
IEnumerator<MyPrivateType> IEnumerable<A.MyPrivateType>.GetEnumerator()
{ throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator()
{ throw new NotImplementedException(); }
}";
var textB = @"
using System.Collections.Generic;
class Z
{
public IEnumerable<object> goo(A a)
{
return a;
}
}";
CSharpCompilation c1 = CreateCompilation(textA);
CSharpCompilation c2 = CreateCompilation(textB, new[] { new CSharpCompilationReference(c1) });
//Works this way, but doesn't when compilation is supplied as metadata
Assert.Equal(0, c1.GetDiagnostics().Count());
Assert.Equal(0, c2.GetDiagnostics().Count());
var metadata1 = c1.EmitToArray(options: new EmitOptions(metadataOnly: true));
c2 = CreateCompilation(textB, new[] { MetadataReference.CreateFromImage(metadata1) });
Assert.Equal(0, c2.GetDiagnostics().Count());
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[Fact()]
public void ProtectedInternalNestedBaseClass()
{
var source1 = @"
public class PublicClass
{
protected internal class ProtectedInternalClass
{
public ProtectedInternalClass()
{
}
}
}
";
var source2 = @"
class C : PublicClass.ProtectedInternalClass
{
}
";
var compilation1 = CreateCompilation(source1, assemblyName: "One");
compilation1.VerifyDiagnostics();
var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }, assemblyName: "Two");
compilation2.VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedInternalClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedInternalClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedInternalClass").WithArguments("PublicClass.ProtectedInternalClass").WithLocation(2, 23)
);
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void ProtectedAndInternalNestedBaseClass()
{
// Note: the problem was with the "protected" check so we use InternalsVisibleTo to make
// the "internal" check succeed.
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string)
= {string('Test')}
}
.class public auto ansi beforefieldinit PublicClass
extends [mscorlib]System.Object
{
.class auto ansi nested famandassem beforefieldinit ProtectedAndInternalClass
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class ProtectedAndInternalClass
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class PublicClass
";
var csharp = @"
class C : PublicClass.ProtectedAndInternalClass
{
}
";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false).VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedAndInternalClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedAndInternalClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedAndInternalClass").WithArguments("PublicClass.ProtectedAndInternalClass").WithLocation(2, 23)
);
}
[WorkItem(530144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530144")]
[Fact()]
public void UnifyingBaseInterfaces01()
{
var il = @"
.assembly extern mscorlib
{
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module a.dll
.class interface public abstract auto ansi J`1<T>
{
}
.class interface public abstract auto ansi I`1<T>
implements class J`1<int32>,
class J`1<!T>
{
}";
var csharp =
@"public class C
{
public static I<int> x;
static void F(I<int> x)
{
I<int> t = C.x;
}
}
public class D : I<int> {}
public interface I2 : I<int> {}";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false).VerifyDiagnostics(
// (4,26): error CS0648: 'I<int>' is a type not supported by the language
// static void F(I<int> x)
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<int>").WithLocation(4, 26),
// (3,26): error CS0648: 'I<int>' is a type not supported by the language
// public static I<int> x;
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<int>").WithLocation(3, 26),
// (10,14): error CS0648: 'I<int>' is a type not supported by the language
// public class D : I<int> {}
Diagnostic(ErrorCode.ERR_BogusType, "D").WithArguments("I<int>").WithLocation(10, 14),
// (11,18): error CS0648: 'I<int>' is a type not supported by the language
// public interface I2 : I<int> {}
Diagnostic(ErrorCode.ERR_BogusType, "I2").WithArguments("I<int>").WithLocation(11, 18),
// (6,9): error CS0648: 'I<int>' is a type not supported by the language
// I<int> t = C.x;
Diagnostic(ErrorCode.ERR_BogusType, "I<int>").WithArguments("I<int>").WithLocation(6, 9)
);
}
[WorkItem(530144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530144")]
[Fact()]
public void UnifyingBaseInterfaces02()
{
var il = @"
.assembly extern mscorlib
{
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module a.dll
.class interface public abstract auto ansi J`1<T>
{
}
.class interface public abstract auto ansi I`1<T>
implements class J`1<object>,
class J`1<!T>
{
}";
var csharp =
@"public class C
{
public static I<dynamic> x;
static void F(I<dynamic> x)
{
I<dynamic> t = C.x;
}
}";
CreateCompilationWithILAndMscorlib40(csharp, il, appendDefaultHeader: false, targetFramework: TargetFramework.Standard).VerifyDiagnostics(
// (4,30): error CS0648: 'I<dynamic>' is a type not supported by the language
// static void F(I<dynamic> x)
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<dynamic>").WithLocation(4, 30),
// (3,30): error CS0648: 'I<dynamic>' is a type not supported by the language
// public static I<dynamic> x;
Diagnostic(ErrorCode.ERR_BogusType, "x").WithArguments("I<dynamic>").WithLocation(3, 30),
// (6,9): error CS0648: 'I<dynamic>' is a type not supported by the language
// I<dynamic> t = C.x;
Diagnostic(ErrorCode.ERR_BogusType, "I<dynamic>").WithArguments("I<dynamic>").WithLocation(6, 9)
);
}
[WorkItem(545365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545365")]
[Fact()]
public void ProtectedNestedBaseClass()
{
var source1 = @"
public class PublicClass
{
protected class ProtectedClass
{
public ProtectedClass()
{
}
}
}
";
var source2 = @"
class C : PublicClass.ProtectedClass
{
}
";
var compilation1 = CreateCompilation(source1, assemblyName: "One");
compilation1.VerifyDiagnostics();
var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }, assemblyName: "Two");
compilation2.VerifyDiagnostics(
// (2,23): error CS0122: 'PublicClass.ProtectedClass' is inaccessible due to its protection level
// class C : PublicClass.ProtectedClass
Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedClass").WithArguments("PublicClass.ProtectedClass"));
}
[WorkItem(545589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545589")]
[Fact]
public void MissingTypeArgumentInBase()
{
var text =
@"interface I<out T> { }
class B : I<object>
{
public static void Goo<T>(I<T> x)
{
}
public static void Goo<T>() where T : I<>
{
}
static void Main()
{
Goo(new B());
}
}";
var comp = CreateCompilation(Parse(text));
comp.VerifyDiagnostics(
// (9,43): error CS7003: Unexpected use of an unbound generic name
// public static void Goo<T>() where T : I<>
Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "I<>")
);
}
[WorkItem(792711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792711")]
[Fact]
public void Repro792711()
{
var source = @"
public class Base<T>
{
}
public class Derived<T> : Base<Derived<T>>
{
}
";
var metadataRef = CreateCompilation(source).EmitToImageReference(embedInteropTypes: true);
var comp = CreateCompilation("", new[] { metadataRef });
var derived = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
Assert.Equal(TypeKind.Class, derived.TypeKind);
}
[WorkItem(872825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872825")]
[Fact]
public void InaccessibleStructInterface()
{
var source =
@"class C
{
protected interface I
{
}
}
struct S : C.I
{
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0122: 'C.I' is inaccessible due to its protection level
// struct S : C.I
Diagnostic(ErrorCode.ERR_BadAccess, "I").WithArguments("C.I").WithLocation(7, 14));
}
[WorkItem(872948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872948")]
[Fact]
public void MissingNestedMemberInStructImplementsClause()
{
var source =
@"struct S : S.I
{
}";
var compilation = CreateCompilation(source);
// Ideally report "CS0426: The type name 'I' does not exist in the type 'S'"
// instead. Bug #896959.
compilation.VerifyDiagnostics(
// (1,14): error CS0146: Circular base type dependency involving 'S' and 'S'
// struct S : S.I
Diagnostic(ErrorCode.ERR_CircularBase, "I").WithArguments("S", "S").WithLocation(1, 14));
}
[WorkItem(896959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896959")]
[Fact(Skip = "896959")]
public void MissingNestedMemberInClassImplementsClause()
{
var source =
@"class C : C.I
{
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (1,13): error CS0426: The type name 'I' does not exist in the type 'C'
// class C : C.I
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "I").WithArguments("I", "C").WithLocation(1, 13));
}
[Fact, WorkItem(1085632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085632")]
public void BaseLookupRecursionWithStaticImport01()
{
const string source =
@"using A<int>.B;
using D;
class A<T> : C
{
public static class B { }
}
class D
{
public class C { }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,14): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?)
// class A<T> : C
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C").WithLocation(4, 14),
// (1,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'A<int>.B' is a type not a namespace. Consider a 'using static' directive instead
// using A<int>.B;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "A<int>.B").WithArguments("A<int>.B").WithLocation(1, 7),
// (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'D' is a type not a namespace. Consider a 'using static' directive instead
// using D;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "D").WithArguments("D").WithLocation(2, 7),
// (2,1): hidden CS8019: Unnecessary using directive.
// using D;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using D;").WithLocation(2, 1),
// (1,1): hidden CS8019: Unnecessary using directive.
// using A<int>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A<int>.B;").WithLocation(1, 1)
);
}
[Fact, WorkItem(1085632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085632")]
public void BaseLookupRecursionWithStaticImport02()
{
const string source =
@"using static A<int>.B;
using static D;
class A<T> : C
{
public static class B { }
}
class D
{
public class C { }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using static A<int>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int>.B;").WithLocation(1, 1)
);
}
[Fact]
public void BindBases()
{
// Ensure good semantic model data even in error scenarios
var text =
@"
class B {
public B(long x) {}
}
class D : B {
extern D(int x) : base(y) {}
static int y;
}";
var comp = CreateCompilationWithMscorlib45(text);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var baseY = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "y").OfType<ExpressionSyntax>().First();
var typeInfo = model.GetTypeInfo(baseY);
Assert.Equal(SpecialType.System_Int32, typeInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_Int64, typeInfo.ConvertedType.SpecialType);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_01()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
CompileAndVerify(comp);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_02()
{
var text =
@"
using static CrashTest.Crash<object>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
class Class3
{
AbstractClass Test()
{
return null;
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,14): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// using static CrashTest.Crash<object>;
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "CrashTest.Crash<object>").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(2, 14),
// (6,11): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// class Class2 : AbstractClass
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Class2").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(6, 11),
// (21,23): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'Crash<T>'. There is no implicit reference conversion from 'object' to 'CrashTest.Crash<object>.AbstractClass'.
// AbstractClass Test()
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Test").WithArguments("CrashTest.Crash<T>", "CrashTest.Crash<object>.AbstractClass", "T", "object").WithLocation(21, 23)
);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_03()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
[System.Obsolete]
class Class2 : AbstractClass
{
}
[System.Obsolete]
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,30): warning CS0612: 'Class2' is obsolete
// using static CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CrashTest.Class2").WithArguments("CrashTest.Class2").WithLocation(2, 30),
// (2,14): warning CS0612: 'Crash<Class2>' is obsolete
// using static CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CrashTest.Crash<CrashTest.Class2>").WithArguments("CrashTest.Crash<CrashTest.Class2>").WithLocation(2, 14));
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_04()
{
var text =
@"
using static CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
[System.Obsolete]
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (11,18): warning CS0612: 'Crash<T>.AbstractClass' is obsolete
// where T: Crash<T>.AbstractClass
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Crash<T>.AbstractClass").WithArguments("CrashTest.Crash<T>.AbstractClass").WithLocation(11, 18),
// (6,20): warning CS0612: 'Crash<Class2>.AbstractClass' is obsolete
// class Class2 : AbstractClass
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "AbstractClass").WithArguments("CrashTest.Crash<CrashTest.Class2>.AbstractClass").WithLocation(6, 20)
);
}
[Fact, WorkItem(5697, "https://github.com/dotnet/roslyn/issues/5697")]
public void InheritThroughStaticImportOfGenericTypeWithConstraint_05()
{
var text =
@"
using CrashTest.Crash<CrashTest.Class2>;
namespace CrashTest
{
class Class2 : AbstractClass
{
}
public static class Crash<T>
where T: Crash<T>.AbstractClass
{
public abstract class AbstractClass
{
public int Id { get; set; }
}
}
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'Crash<Class2>' is a type not a namespace. Consider a 'using static' directive instead
// using CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.ERR_BadUsingNamespace, "CrashTest.Crash<CrashTest.Class2>").WithArguments("CrashTest.Crash<CrashTest.Class2>").WithLocation(2, 7),
// (6,20): error CS0246: The type or namespace name 'AbstractClass' could not be found (are you missing a using directive or an assembly reference?)
// class Class2 : AbstractClass
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "AbstractClass").WithArguments("AbstractClass").WithLocation(6, 20),
// (2,1): hidden CS8019: Unnecessary using directive.
// using CrashTest.Crash<CrashTest.Class2>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using CrashTest.Crash<CrashTest.Class2>;").WithLocation(2, 1)
);
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CycleTypeArgument()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C>.B { }
class F : A<D>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17));
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CycleArray()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C[]>.B { }
class F : A<D[]>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17));
}
[Fact]
[WorkItem(174789, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=174789")]
public void CyclePointer()
{
var text =
@"class A<T>
{
internal class B { }
}
class Base
{
protected class C { }
private class D { }
}
class Derived : Base
{
class E : A<C*>.B { }
class F : A<D*>.B { }
}";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (13,17): error CS0122: 'Base.D' is inaccessible due to its protection level
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_BadAccess, "D").WithArguments("Base.D").WithLocation(13, 17),
// (13,11): error CS0306: The type 'Base.D*' may not be used as a type argument
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("Base.D*").WithLocation(13, 11),
// (13,11): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Base.D')
// class F : A<D*>.B { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "F").WithArguments("Base.D").WithLocation(13, 11),
// (12,11): error CS0306: The type 'Base.C*' may not be used as a type argument
// class E : A<C*>.B { }
Diagnostic(ErrorCode.ERR_BadTypeArgument, "E").WithArguments("Base.C*").WithLocation(12, 11),
// (12,11): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Base.C')
// class E : A<C*>.B { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "E").WithArguments("Base.C").WithLocation(12, 11));
}
[Fact]
[WorkItem(1107185, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107185")]
public void Tuple_MissingNestedTypeArgument_01()
{
var source =
@"interface I<T>
{
}
class A : I<(object, A.B)>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,24): error CS0146: Circular base type dependency involving 'A' and 'A'
// class A : I<(object, A.B)>
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "A").WithLocation(4, 24));
}
[Fact]
[WorkItem(1107185, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107185")]
public void Tuple_MissingNestedTypeArgument_02()
{
var source =
@"class A<T>
{
}
class B : A<(object, B.C)>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,24): error CS0146: Circular base type dependency involving 'B' and 'B'
// class B : A<(object, B.C)>
Diagnostic(ErrorCode.ERR_CircularBase, "C").WithArguments("B", "B").WithLocation(4, 24));
}
[Fact]
public void Tuple_MissingNestedTypeArgument_03()
{
var source =
@"interface I<T>
{
}
class A : I<System.ValueTuple<object, A.B>>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,41): error CS0146: Circular base type dependency involving 'A' and 'A'
// class A : I<System.ValueTuple<object, A.B>>
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A", "A").WithLocation(4, 41));
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/CodeFixes/Supression/IConfigurationFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Provides suppression or configuration code fixes.
/// </summary>
internal interface IConfigurationFixProvider
{
/// <summary>
/// Returns true if the given diagnostic can be configured, suppressed or unsuppressed by this provider.
/// </summary>
bool IsFixableDiagnostic(Diagnostic diagnostic);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified no-location diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
FixAllProvider? GetFixAllProvider();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Provides suppression or configuration code fixes.
/// </summary>
internal interface IConfigurationFixProvider
{
/// <summary>
/// Returns true if the given diagnostic can be configured, suppressed or unsuppressed by this provider.
/// </summary>
bool IsFixableDiagnostic(Diagnostic diagnostic);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets one or more add suppression, remove suppression, or configuration fixes for the specified no-location diagnostics represented as a list of <see cref="CodeAction"/>'s.
/// </summary>
/// <returns>A list of zero or more potential <see cref="CodeFix"/>'es. It is also safe to return null if there are none.</returns>
Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
FixAllProvider? GetFixAllProvider();
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IEndOperation.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main() 'BIND:"Shared Sub Main"
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
x = 1
End
x = 2
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (ProgramTermination) Block[null]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Block[B3] - Exit [UnReachable]
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
Try
x = 1
Finally
End
End Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (0)
Next (ProgramTermination) Block[null]
}
Block[B3] - Exit [UnReachable]
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
x = 1
GoTo label1
label1:
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Boolean) 'BIND:"Sub M"
If x Then GoTo label1
label1:
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_06()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main() 'BIND:"Shared Sub Main"
If True
Dim x As Integer = 1
End If
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [x As System.Int32]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer = 1')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Next (ProgramTermination) Block[null]
Block[B4] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_07()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then End
End
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_08()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then End
Return
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (ProgramTermination) Block[null]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_09()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then Return
End
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_10()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
Try
End
Finally
x = 1
End Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (ProgramTermination) Block[null]
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (StructuredExceptionHandling) Block[null]
}
Block[B3] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
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.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main() 'BIND:"Shared Sub Main"
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
x = 1
End
x = 2
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (ProgramTermination) Block[null]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Block[B3] - Exit [UnReachable]
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
Try
x = 1
Finally
End
End Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (0)
Next (ProgramTermination) Block[null]
}
Block[B3] - Exit [UnReachable]
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
x = 1
GoTo label1
label1:
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Boolean) 'BIND:"Sub M"
If x Then GoTo label1
label1:
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_06()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main() 'BIND:"Shared Sub Main"
If True
Dim x As Integer = 1
End If
End
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [x As System.Int32]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer = 1')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Next (ProgramTermination) Block[null]
Block[B4] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_07()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then End
End
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (ProgramTermination) Block[null]
Block[B2] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_08()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then End
Return
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (ProgramTermination) Block[null]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_09()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer, a As Boolean) 'BIND:"Sub M"
x = 2
GoTo label2
label1:
If a Then Return
End
label2:
GoTo label1
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 2')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Jump if False (ProgramTermination) to Block[null]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub EndFlow_10()
Dim source = <![CDATA[
Imports System
Public Class C
Shared Sub Main()
End Sub
Sub M(x As Integer) 'BIND:"Sub M"
Try
End
Finally
x = 1
End Try
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (ProgramTermination) Block[null]
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (StructuredExceptionHandling) Block[null]
}
Block[B3] - Exit [UnReachable]
Predecessors (0)
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseExe)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/FileSystem/FileUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Roslyn.Utilities
{
internal static class FileUtilities
{
/// <summary>
/// Resolves relative path and returns absolute path.
/// The method depends only on values of its parameters and their implementation (for fileExists).
/// It doesn't itself depend on the state of the current process (namely on the current drive directories) or
/// the state of file system.
/// </summary>
/// <param name="path">
/// Path to resolve.
/// </param>
/// <param name="basePath">
/// Base file path to resolve CWD-relative paths against. Null if not available.
/// </param>
/// <param name="baseDirectory">
/// Base directory to resolve CWD-relative paths against if <paramref name="basePath"/> isn't specified.
/// Must be absolute path.
/// Null if not available.
/// </param>
/// <param name="searchPaths">
/// Sequence of paths used to search for unqualified relative paths.
/// </param>
/// <param name="fileExists">
/// Method that tests existence of a file.
/// </param>
/// <returns>
/// The resolved path or null if the path can't be resolved or does not exist.
/// </returns>
internal static string? ResolveRelativePath(
string path,
string? basePath,
string? baseDirectory,
IEnumerable<string> searchPaths,
Func<string, bool> fileExists)
{
Debug.Assert(baseDirectory == null || searchPaths != null || PathUtilities.IsAbsolute(baseDirectory));
RoslynDebug.Assert(searchPaths != null);
RoslynDebug.Assert(fileExists != null);
string? combinedPath;
var kind = PathUtilities.GetPathKind(path);
if (kind == PathKind.Relative)
{
// first, look in the base directory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory != null)
{
combinedPath = PathUtilities.CombinePathsUnchecked(baseDirectory, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
// try search paths:
foreach (var searchPath in searchPaths)
{
combinedPath = PathUtilities.CombinePathsUnchecked(searchPath, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
combinedPath = ResolveRelativePath(kind, path, basePath, baseDirectory);
if (combinedPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
internal static string? ResolveRelativePath(string? path, string? baseDirectory)
{
return ResolveRelativePath(path, null, baseDirectory);
}
internal static string? ResolveRelativePath(string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(baseDirectory == null || PathUtilities.IsAbsolute(baseDirectory));
return ResolveRelativePath(PathUtilities.GetPathKind(path), path, basePath, baseDirectory);
}
private static string? ResolveRelativePath(PathKind kind, string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(PathUtilities.GetPathKind(path) == kind);
switch (kind)
{
case PathKind.Empty:
return null;
case PathKind.Relative:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// with no search paths relative paths are relative to the base directory:
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentDirectory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
if (path!.Length == 1)
{
// "."
return baseDirectory;
}
else
{
// ".\path"
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
}
case PathKind.RelativeToCurrentParent:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// ".."
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentRoot:
string? baseRoot;
if (basePath != null)
{
baseRoot = PathUtilities.GetPathRoot(basePath);
}
else if (baseDirectory != null)
{
baseRoot = PathUtilities.GetPathRoot(baseDirectory);
}
else
{
return null;
}
if (RoslynString.IsNullOrEmpty(baseRoot))
{
return null;
}
Debug.Assert(PathUtilities.IsDirectorySeparator(path![0]));
Debug.Assert(path.Length == 1 || !PathUtilities.IsDirectorySeparator(path[1]));
return PathUtilities.CombinePathsUnchecked(baseRoot, path.Substring(1));
case PathKind.RelativeToDriveDirectory:
// drive relative paths not supported, can't resolve:
return null;
case PathKind.Absolute:
return path;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private static string? GetBaseDirectory(string? basePath, string? baseDirectory)
{
// relative base paths are relative to the base directory:
string? resolvedBasePath = ResolveRelativePath(basePath, baseDirectory);
if (resolvedBasePath == null)
{
return baseDirectory;
}
// Note: Path.GetDirectoryName doesn't normalize the path and so it doesn't depend on the process state.
Debug.Assert(PathUtilities.IsAbsolute(resolvedBasePath));
try
{
return Path.GetDirectoryName(resolvedBasePath);
}
catch (Exception)
{
return null;
}
}
private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars();
internal static string? NormalizeRelativePath(string path, string? basePath, string? baseDirectory)
{
// Does this look like a URI at all or does it have any invalid path characters? If so, just use it as is.
if (path.IndexOf("://", StringComparison.Ordinal) >= 0 || path.IndexOfAny(s_invalidPathChars) >= 0)
{
return null;
}
string? resolvedPath = ResolveRelativePath(path, basePath, baseDirectory);
if (resolvedPath == null)
{
return null;
}
string? normalizedPath = TryNormalizeAbsolutePath(resolvedPath);
if (normalizedPath == null)
{
return null;
}
return normalizedPath;
}
/// <summary>
/// Normalizes an absolute path.
/// </summary>
/// <param name="path">Path to normalize.</param>
/// <exception cref="IOException"/>
/// <returns>Normalized path.</returns>
internal static string NormalizeAbsolutePath(string path)
{
// we can only call GetFullPath on an absolute path to avoid dependency on process state (current directory):
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch (ArgumentException e)
{
throw new IOException(e.Message, e);
}
catch (System.Security.SecurityException e)
{
throw new IOException(e.Message, e);
}
catch (NotSupportedException e)
{
throw new IOException(e.Message, e);
}
}
internal static string NormalizeDirectoryPath(string path)
{
return NormalizeAbsolutePath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
internal static string? TryNormalizeAbsolutePath(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch
{
return null;
}
}
internal static Stream OpenRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
internal static Stream OpenAsyncRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
return RethrowExceptionsAsIOException(() => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous));
}
internal static T RethrowExceptionsAsIOException<T>(Func<T> operation)
{
try
{
return operation();
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <summary>
/// Used to create a file given a path specified by the user.
/// paramName - Provided by the Public surface APIs to have a clearer message. Internal API just rethrow the exception
/// </summary>
internal static Stream CreateFileStreamChecked(Func<string, Stream> factory, string path, string? paramName = null)
{
try
{
return factory(path);
}
catch (ArgumentNullException)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentNullException(paramName);
}
}
catch (ArgumentException e)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentException(e.Message, paramName);
}
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static DateTime GetFileTimeStamp(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return File.GetLastWriteTimeUtc(fullPath);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static long GetFileLength(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
var info = new FileInfo(fullPath);
return info.Length;
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Roslyn.Utilities
{
internal static class FileUtilities
{
/// <summary>
/// Resolves relative path and returns absolute path.
/// The method depends only on values of its parameters and their implementation (for fileExists).
/// It doesn't itself depend on the state of the current process (namely on the current drive directories) or
/// the state of file system.
/// </summary>
/// <param name="path">
/// Path to resolve.
/// </param>
/// <param name="basePath">
/// Base file path to resolve CWD-relative paths against. Null if not available.
/// </param>
/// <param name="baseDirectory">
/// Base directory to resolve CWD-relative paths against if <paramref name="basePath"/> isn't specified.
/// Must be absolute path.
/// Null if not available.
/// </param>
/// <param name="searchPaths">
/// Sequence of paths used to search for unqualified relative paths.
/// </param>
/// <param name="fileExists">
/// Method that tests existence of a file.
/// </param>
/// <returns>
/// The resolved path or null if the path can't be resolved or does not exist.
/// </returns>
internal static string? ResolveRelativePath(
string path,
string? basePath,
string? baseDirectory,
IEnumerable<string> searchPaths,
Func<string, bool> fileExists)
{
Debug.Assert(baseDirectory == null || searchPaths != null || PathUtilities.IsAbsolute(baseDirectory));
RoslynDebug.Assert(searchPaths != null);
RoslynDebug.Assert(fileExists != null);
string? combinedPath;
var kind = PathUtilities.GetPathKind(path);
if (kind == PathKind.Relative)
{
// first, look in the base directory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory != null)
{
combinedPath = PathUtilities.CombinePathsUnchecked(baseDirectory, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
// try search paths:
foreach (var searchPath in searchPaths)
{
combinedPath = PathUtilities.CombinePathsUnchecked(searchPath, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
combinedPath = ResolveRelativePath(kind, path, basePath, baseDirectory);
if (combinedPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
internal static string? ResolveRelativePath(string? path, string? baseDirectory)
{
return ResolveRelativePath(path, null, baseDirectory);
}
internal static string? ResolveRelativePath(string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(baseDirectory == null || PathUtilities.IsAbsolute(baseDirectory));
return ResolveRelativePath(PathUtilities.GetPathKind(path), path, basePath, baseDirectory);
}
private static string? ResolveRelativePath(PathKind kind, string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(PathUtilities.GetPathKind(path) == kind);
switch (kind)
{
case PathKind.Empty:
return null;
case PathKind.Relative:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// with no search paths relative paths are relative to the base directory:
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentDirectory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
if (path!.Length == 1)
{
// "."
return baseDirectory;
}
else
{
// ".\path"
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
}
case PathKind.RelativeToCurrentParent:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// ".."
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentRoot:
string? baseRoot;
if (basePath != null)
{
baseRoot = PathUtilities.GetPathRoot(basePath);
}
else if (baseDirectory != null)
{
baseRoot = PathUtilities.GetPathRoot(baseDirectory);
}
else
{
return null;
}
if (RoslynString.IsNullOrEmpty(baseRoot))
{
return null;
}
Debug.Assert(PathUtilities.IsDirectorySeparator(path![0]));
Debug.Assert(path.Length == 1 || !PathUtilities.IsDirectorySeparator(path[1]));
return PathUtilities.CombinePathsUnchecked(baseRoot, path.Substring(1));
case PathKind.RelativeToDriveDirectory:
// drive relative paths not supported, can't resolve:
return null;
case PathKind.Absolute:
return path;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private static string? GetBaseDirectory(string? basePath, string? baseDirectory)
{
// relative base paths are relative to the base directory:
string? resolvedBasePath = ResolveRelativePath(basePath, baseDirectory);
if (resolvedBasePath == null)
{
return baseDirectory;
}
// Note: Path.GetDirectoryName doesn't normalize the path and so it doesn't depend on the process state.
Debug.Assert(PathUtilities.IsAbsolute(resolvedBasePath));
try
{
return Path.GetDirectoryName(resolvedBasePath);
}
catch (Exception)
{
return null;
}
}
private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars();
internal static string? NormalizeRelativePath(string path, string? basePath, string? baseDirectory)
{
// Does this look like a URI at all or does it have any invalid path characters? If so, just use it as is.
if (path.IndexOf("://", StringComparison.Ordinal) >= 0 || path.IndexOfAny(s_invalidPathChars) >= 0)
{
return null;
}
string? resolvedPath = ResolveRelativePath(path, basePath, baseDirectory);
if (resolvedPath == null)
{
return null;
}
string? normalizedPath = TryNormalizeAbsolutePath(resolvedPath);
if (normalizedPath == null)
{
return null;
}
return normalizedPath;
}
/// <summary>
/// Normalizes an absolute path.
/// </summary>
/// <param name="path">Path to normalize.</param>
/// <exception cref="IOException"/>
/// <returns>Normalized path.</returns>
internal static string NormalizeAbsolutePath(string path)
{
// we can only call GetFullPath on an absolute path to avoid dependency on process state (current directory):
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch (ArgumentException e)
{
throw new IOException(e.Message, e);
}
catch (System.Security.SecurityException e)
{
throw new IOException(e.Message, e);
}
catch (NotSupportedException e)
{
throw new IOException(e.Message, e);
}
}
internal static string NormalizeDirectoryPath(string path)
{
return NormalizeAbsolutePath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
internal static string? TryNormalizeAbsolutePath(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch
{
return null;
}
}
internal static Stream OpenRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
internal static Stream OpenAsyncRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
return RethrowExceptionsAsIOException(() => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous));
}
internal static T RethrowExceptionsAsIOException<T>(Func<T> operation)
{
try
{
return operation();
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <summary>
/// Used to create a file given a path specified by the user.
/// paramName - Provided by the Public surface APIs to have a clearer message. Internal API just rethrow the exception
/// </summary>
internal static Stream CreateFileStreamChecked(Func<string, Stream> factory, string path, string? paramName = null)
{
try
{
return factory(path);
}
catch (ArgumentNullException)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentNullException(paramName);
}
}
catch (ArgumentException e)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentException(e.Message, paramName);
}
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static DateTime GetFileTimeStamp(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return File.GetLastWriteTimeUtc(fullPath);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static long GetFileLength(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
var info = new FileInfo(fullPath);
return info.Length;
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/MSBuildTask/GenerateMSBuildEditorConfig.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.
/// </summary>
/// <remarks>
/// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms
/// them into a global analyzer config.
///
/// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name
/// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ]
/// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the
/// global section of the generated config file.
///
/// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the
/// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally
/// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of
/// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given
/// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>.
///
/// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section
/// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a
/// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c>
///
/// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and
/// <c>AnalyzerItemMetadata</c> item groups.
/// </remarks>
public sealed class GenerateMSBuildEditorConfig : Task
{
/// <remarks>
/// Although this task does its own writing to disk, this
/// output parameter is here for testing purposes.
/// </remarks>
[Output]
public string ConfigFileContents { get; set; }
[Required]
public ITaskItem[] MetadataItems { get; set; }
[Required]
public ITaskItem[] PropertyItems { get; set; }
public ITaskItem FileName { get; set; }
public GenerateMSBuildEditorConfig()
{
ConfigFileContents = string.Empty;
MetadataItems = Array.Empty<ITaskItem>();
PropertyItems = Array.Empty<ITaskItem>();
FileName = new TaskItem();
}
public override bool Execute()
{
StringBuilder builder = new StringBuilder();
// we always generate global configs
builder.AppendLine("is_global = true");
// collect the properties into a global section
foreach (var prop in PropertyItems)
{
builder.Append("build_property.")
.Append(prop.ItemSpec)
.Append(" = ")
.AppendLine(prop.GetMetadata("Value"));
}
// group the metadata items by their full path
var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath")));
foreach (var group in groupedItems)
{
// write the section for this item
builder.AppendLine()
.Append("[");
EncodeString(builder, group.Key);
builder.AppendLine("]");
foreach (var item in group)
{
string itemType = item.GetMetadata("ItemType");
string metadataName = item.GetMetadata("MetadataName");
if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))
{
builder.Append("build_metadata.")
.Append(itemType)
.Append(".")
.Append(metadataName)
.Append(" = ")
.AppendLine(item.GetMetadata(metadataName));
}
}
}
ConfigFileContents = builder.ToString();
return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig();
}
internal bool WriteMSBuildEditorConfig()
{
try
{
var targetFileName = FileName.ItemSpec;
if (File.Exists(targetFileName))
{
string existingContents = File.ReadAllText(targetFileName);
if (existingContents.Equals(ConfigFileContents))
{
return true;
}
}
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
File.WriteAllText(targetFileName, ConfigFileContents, encoding);
return true;
}
catch (IOException ex)
{
Log.LogErrorFromException(ex);
return false;
}
}
/// <remarks>
/// Filenames with special characters like '#' and'{' get written
/// into the section names in the resulting .editorconfig file. Later,
/// when the file is parsed in configuration options these special
/// characters are interpretted as invalid values and ignored by the
/// processor. We encode the special characters in these strings
/// before writing them here.
/// </remarks>
private static void EncodeString(StringBuilder builder, string value)
{
foreach (var c in value)
{
if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')
{
builder.Append("\\");
}
builder.Append(c);
}
}
/// <remarks>
/// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash
/// Both methods should be kept in sync.
/// </remarks>
private static string NormalizeWithForwardSlash(string p)
=> PlatformInformation.IsUnix ? p : p.Replace('\\', '/');
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.
/// </summary>
/// <remarks>
/// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms
/// them into a global analyzer config.
///
/// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name
/// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ]
/// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the
/// global section of the generated config file.
///
/// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the
/// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally
/// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of
/// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given
/// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>.
///
/// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section
/// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a
/// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c>
///
/// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and
/// <c>AnalyzerItemMetadata</c> item groups.
/// </remarks>
public sealed class GenerateMSBuildEditorConfig : Task
{
/// <remarks>
/// Although this task does its own writing to disk, this
/// output parameter is here for testing purposes.
/// </remarks>
[Output]
public string ConfigFileContents { get; set; }
[Required]
public ITaskItem[] MetadataItems { get; set; }
[Required]
public ITaskItem[] PropertyItems { get; set; }
public ITaskItem FileName { get; set; }
public GenerateMSBuildEditorConfig()
{
ConfigFileContents = string.Empty;
MetadataItems = Array.Empty<ITaskItem>();
PropertyItems = Array.Empty<ITaskItem>();
FileName = new TaskItem();
}
public override bool Execute()
{
StringBuilder builder = new StringBuilder();
// we always generate global configs
builder.AppendLine("is_global = true");
// collect the properties into a global section
foreach (var prop in PropertyItems)
{
builder.Append("build_property.")
.Append(prop.ItemSpec)
.Append(" = ")
.AppendLine(prop.GetMetadata("Value"));
}
// group the metadata items by their full path
var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath")));
foreach (var group in groupedItems)
{
// write the section for this item
builder.AppendLine()
.Append("[");
EncodeString(builder, group.Key);
builder.AppendLine("]");
foreach (var item in group)
{
string itemType = item.GetMetadata("ItemType");
string metadataName = item.GetMetadata("MetadataName");
if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))
{
builder.Append("build_metadata.")
.Append(itemType)
.Append(".")
.Append(metadataName)
.Append(" = ")
.AppendLine(item.GetMetadata(metadataName));
}
}
}
ConfigFileContents = builder.ToString();
return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig();
}
internal bool WriteMSBuildEditorConfig()
{
try
{
var targetFileName = FileName.ItemSpec;
if (File.Exists(targetFileName))
{
string existingContents = File.ReadAllText(targetFileName);
if (existingContents.Equals(ConfigFileContents))
{
return true;
}
}
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
File.WriteAllText(targetFileName, ConfigFileContents, encoding);
return true;
}
catch (IOException ex)
{
Log.LogErrorFromException(ex);
return false;
}
}
/// <remarks>
/// Filenames with special characters like '#' and'{' get written
/// into the section names in the resulting .editorconfig file. Later,
/// when the file is parsed in configuration options these special
/// characters are interpretted as invalid values and ignored by the
/// processor. We encode the special characters in these strings
/// before writing them here.
/// </remarks>
private static void EncodeString(StringBuilder builder, string value)
{
foreach (var c in value)
{
if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')
{
builder.Append("\\");
}
builder.Append(c);
}
}
/// <remarks>
/// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash
/// Both methods should be kept in sync.
/// </remarks>
private static string NormalizeWithForwardSlash(string p)
=> PlatformInformation.IsUnix ? p : p.Replace('\\', '/');
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/CSharp/Test/CommandLine/GeneratorDriverCacheTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class GeneratorDriverCacheTests : CommandLineTestBase
{
[Fact]
public void DriverCache_Returns_Null_For_No_Match()
{
var driverCache = new GeneratorDriverCache();
var driver = driverCache.TryGetDriver("0");
Assert.Null(driver);
}
[Fact]
public void DriverCache_Returns_Cached_Driver()
{
var drivers = GetDrivers(1);
var driverCache = new GeneratorDriverCache();
driverCache.CacheGenerator("0", drivers[0]);
var driver = driverCache.TryGetDriver("0");
Assert.Same(driver, drivers[0]);
}
[Fact]
public void DriverCache_Can_Cache_Multiple_Drivers()
{
var drivers = GetDrivers(3);
var driverCache = new GeneratorDriverCache();
driverCache.CacheGenerator("0", drivers[0]);
driverCache.CacheGenerator("1", drivers[1]);
driverCache.CacheGenerator("2", drivers[2]);
var driver = driverCache.TryGetDriver("0");
Assert.Same(driver, drivers[0]);
driver = driverCache.TryGetDriver("1");
Assert.Same(driver, drivers[1]);
driver = driverCache.TryGetDriver("2");
Assert.Same(driver, drivers[2]);
}
[Fact]
public void DriverCache_Evicts_Least_Recently_Used()
{
var drivers = GetDrivers(GeneratorDriverCache.MaxCacheSize + 2);
var driverCache = new GeneratorDriverCache();
// put n+1 drivers into the cache
for (int i = 0; i < GeneratorDriverCache.MaxCacheSize + 1; i++)
{
driverCache.CacheGenerator(i.ToString(), drivers[i]);
}
// current cache state is
// (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
// now try and retrieve the first driver which should no longer be in the cache
var driver = driverCache.TryGetDriver("0");
Assert.Null(driver);
// add it back
driverCache.CacheGenerator("0", drivers[0]);
// current cache state is
// (0, 10, 9, 8, 7, 6, 5, 4, 3, 2)
// access some drivers in the middle
driver = driverCache.TryGetDriver("7");
driver = driverCache.TryGetDriver("4");
driver = driverCache.TryGetDriver("2");
// current cache state is
// (2, 4, 7, 0, 10, 9, 8, 6, 5, 3)
// try and get a new driver that was never in the cache
driver = driverCache.TryGetDriver("11");
Assert.Null(driver);
driverCache.CacheGenerator("11", drivers[11]);
// current cache state is
// (11, 2, 4, 7, 0, 10, 9, 8, 6, 5)
// get a driver that has been evicted
driver = driverCache.TryGetDriver("3");
Assert.Null(driver);
}
private static GeneratorDriver[] GetDrivers(int count) => Enumerable.Range(0, count).Select(i => CSharpGeneratorDriver.Create(Array.Empty<ISourceGenerator>())).ToArray();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class GeneratorDriverCacheTests : CommandLineTestBase
{
[Fact]
public void DriverCache_Returns_Null_For_No_Match()
{
var driverCache = new GeneratorDriverCache();
var driver = driverCache.TryGetDriver("0");
Assert.Null(driver);
}
[Fact]
public void DriverCache_Returns_Cached_Driver()
{
var drivers = GetDrivers(1);
var driverCache = new GeneratorDriverCache();
driverCache.CacheGenerator("0", drivers[0]);
var driver = driverCache.TryGetDriver("0");
Assert.Same(driver, drivers[0]);
}
[Fact]
public void DriverCache_Can_Cache_Multiple_Drivers()
{
var drivers = GetDrivers(3);
var driverCache = new GeneratorDriverCache();
driverCache.CacheGenerator("0", drivers[0]);
driverCache.CacheGenerator("1", drivers[1]);
driverCache.CacheGenerator("2", drivers[2]);
var driver = driverCache.TryGetDriver("0");
Assert.Same(driver, drivers[0]);
driver = driverCache.TryGetDriver("1");
Assert.Same(driver, drivers[1]);
driver = driverCache.TryGetDriver("2");
Assert.Same(driver, drivers[2]);
}
[Fact]
public void DriverCache_Evicts_Least_Recently_Used()
{
var drivers = GetDrivers(GeneratorDriverCache.MaxCacheSize + 2);
var driverCache = new GeneratorDriverCache();
// put n+1 drivers into the cache
for (int i = 0; i < GeneratorDriverCache.MaxCacheSize + 1; i++)
{
driverCache.CacheGenerator(i.ToString(), drivers[i]);
}
// current cache state is
// (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
// now try and retrieve the first driver which should no longer be in the cache
var driver = driverCache.TryGetDriver("0");
Assert.Null(driver);
// add it back
driverCache.CacheGenerator("0", drivers[0]);
// current cache state is
// (0, 10, 9, 8, 7, 6, 5, 4, 3, 2)
// access some drivers in the middle
driver = driverCache.TryGetDriver("7");
driver = driverCache.TryGetDriver("4");
driver = driverCache.TryGetDriver("2");
// current cache state is
// (2, 4, 7, 0, 10, 9, 8, 6, 5, 3)
// try and get a new driver that was never in the cache
driver = driverCache.TryGetDriver("11");
Assert.Null(driver);
driverCache.CacheGenerator("11", drivers[11]);
// current cache state is
// (11, 2, 4, 7, 0, 10, 9, 8, 6, 5)
// get a driver that has been evicted
driver = driverCache.TryGetDriver("3");
Assert.Null(driver);
}
private static GeneratorDriver[] GetDrivers(int count) => Enumerable.Range(0, count).Select(i => CSharpGeneratorDriver.Create(Array.Empty<ISourceGenerator>())).ToArray();
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer
Inherits AbstractEditAndContinueAnalyzer
<ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]>
Private NotInheritable Class Factory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing)
End Function
End Class
' Public for testing purposes
Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing)
MyBase.New(testFaultInjector)
End Sub
#Region "Syntax Analysis"
Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean
Dim current = node
While current IsNot rootOpt
Select Case current.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
declarations = OneOrMany.Create(current)
Return True
Case SyntaxKind.PropertyStatement
' Property a As Integer = 1
' Property a As New T
If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then
declarations = OneOrMany.Create(current)
Return True
End If
Case SyntaxKind.VariableDeclarator
If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Dim variableDeclarator = CType(current, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count = 1 Then
declarations = OneOrMany.Create(current)
Else
declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode)))
End If
Return True
End If
Case SyntaxKind.ModifiedIdentifier
If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
declarations = OneOrMany.Create(current)
Return True
End If
End Select
current = current.Parent
End While
declarations = Nothing
Return False
End Function
''' <summary>
''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean
Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
''' <summary>
''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean
Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1
End Function
''' <returns>
''' Given a node representing a declaration or a top-level edit node returns:
''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors.
''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause.
''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer".
''' A null reference otherwise.
''' </returns>
Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node
Case SyntaxKind.PropertyStatement
' the body is the initializer expression/new expression (if any)
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return propertyStatement.Initializer.Value
End If
If HasAsNewClause(propertyStatement) Then
Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
Dim body As SyntaxNode = Nothing
If variableDeclarator.Initializer IsNot Nothing Then
' Dim a = initializer
body = variableDeclarator.Initializer.Value
ElseIf HasAsNewClause(variableDeclarator) Then
' Dim a As New T
' Dim a,b As New T
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As T
If variableDeclarator.Names.Count = 1 Then
Dim name = variableDeclarator.Names(0)
If name.ArrayBounds IsNot Nothing Then
' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, name.ArrayBounds, Nothing)
End If
End If
Return body
Case SyntaxKind.ModifiedIdentifier
If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax)
Dim body As SyntaxNode = Nothing
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing)
End If
Return body
Case Else
' Note: A method without body is represented by a SubStatement.
Return Nothing
End Select
End Function
Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean
If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then
Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax)
Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator)
End If
Return False
End Function
Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol)
Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
If methodBlock.Statements.IsEmpty Then
Return ImmutableArray(Of ISymbol).Empty
End If
Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured
End If
Dim expression = TryCast(memberBody, ExpressionSyntax)
If expression IsNot Nothing Then
Return model.AnalyzeDataFlow(expression).Captured
End If
' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me".
' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer
Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax)
If arrayBounds IsNot Nothing Then
Return ImmutableArray.CreateRange(
arrayBounds.Arguments.
SelectMany(AddressOf GetArgumentExpressions).
SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured).
Distinct())
End If
Throw ExceptionUtilities.UnexpectedValue(memberBody)
End Function
Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax)
Select Case argument.Kind
Case SyntaxKind.SimpleArgument
Yield DirectCast(argument, SimpleArgumentSyntax).Expression
Case SyntaxKind.RangeArgument
Dim range = DirectCast(argument, RangeArgumentSyntax)
Yield range.LowerBound
Yield range.UpperBound
Case SyntaxKind.OmittedArgument
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
End Function
Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean
Return False
End Function
Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode)
Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol)
' Not supported (it's non trivial to find all places where "this" is used):
Debug.Assert(Not localOrParameter.IsThisParameter())
Return From root In roots
From node In root.DescendantNodesAndSelf()
Where node.IsKind(SyntaxKind.IdentifierName)
Let identifier = DirectCast(node, IdentifierNameSyntax)
Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso
If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False)
Select node
End Function
Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean
Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
''' <returns>
''' Methods, operators, constructors, property and event accessors:
''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans.
''' Field declarations in form of "Dim a, b, c As New C()"
''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas.
''' For simplicity we don't allow moving the new expression independently of the field name.
''' Field declarations with array initializers "Dim a(n), b(n) As Integer"
''' - Breakpoint spans cover "a(n)" and "b(n)".
''' </returns>
Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken)
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node.DescendantTokens()
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(),
Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens())
End If
If HasAsNewClause(propertyStatement) Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens())
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If Not IsFieldDeclaration(variableDeclarator) Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
If Not IsFieldDeclaration(modifiedIdentifier) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens())
End If
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return node.DescendantTokens()
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan)
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return (declaration.Span, Nothing)
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing)
End If
If HasAsNewClause(propertyStatement) Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing)
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax)
If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax)
Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End),
hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start))
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax)
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (declaration.Span, Nothing)
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode
' AsNewClause is a match root for field/property As New initializer
' EqualsClause is a match root for field/property initializer
If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement))
Return bodyOrMatchRoot.Parent
End If
' ArgumentList is a match root for an array initialized field
If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return bodyOrMatchRoot.Parent
End If
' The following active nodes are outside of the initializer body,
' we need to return a node that encompasses them.
' Dim [|a = <<Body>>|]
' Dim [|a As Integer = <<Body>>|]
' Dim [|a As <<Body>>|]
' Dim [|a|], [|b|], [|c|] As <<Body>>
' Property [|P As Integer = <<Body>>|]
' Property [|P As <<Body>>|]
If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then
Return bodyOrMatchRoot.Parent.Parent
End If
Return bodyOrMatchRoot
End Function
Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode,
span As TextSpan,
partnerDeclarationBodyOpt As SyntaxNode,
<Out> ByRef partnerOpt As SyntaxNode,
<Out> ByRef statementPart As Integer) As SyntaxNode
Dim position = span.Start
SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False)
Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind)
' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>.
' Simple field initializers: Dim [|a = <<expr>>|]
' Dim [|a As Integer = <<expr>>|]
' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|]
' Dim [|a As <<New C>>|]
' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer
' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>>
' Property initializers: Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If position < declarationBody.SpanStart Then
If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
Return declarationBody.Parent.Parent
End If
If declarationBody.IsKind(SyntaxKind.ArgumentList) Then
' Dim a<<ArgumentList>> As Integer
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent
End If
Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return declarationBody.Parent
End If
If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then
Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
' Dim a, b, c As <<NewExpression>>
Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position)
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex)
End If
Return variableDeclarator.Names(nameIndex)
Else
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
' Dim a As <<NewExpression>>
Return variableDeclarator
End If
End If
If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Return declarationBody.Parent.Parent
End If
End If
If Not declarationBody.FullSpan.Contains(position) Then
' invalid position, let's find a labeled node that encompasses the body:
position = declarationBody.SpanStart
End If
Dim node As SyntaxNode = Nothing
If partnerDeclarationBodyOpt IsNot Nothing Then
SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt)
Else
node = declarationBody.FindToken(position).Parent
partnerOpt = Nothing
End If
' In some cases active statements may start at the same position.
' Consider a nested lambda:
' Function(a) [|[|Function(b)|] a + b|]
' There are 2 active statements, one spanning the the body of the outer lambda and
' the other on the nested lambda's header.
' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length.
While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position
node = node.Parent
partnerOpt = partnerOpt?.Parent
End While
Debug.Assert(node IsNot Nothing)
While node IsNot declarationBody AndAlso
Not SyntaxComparer.Statement.HasLabel(node) AndAlso
Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node)
node = node.Parent
If partnerOpt IsNot Nothing Then
partnerOpt = partnerOpt.Parent
End If
End While
' In case of local variable declaration an active statement may start with a modified identifier.
' If it is a declaration with a simple initializer we want the resulting statement to be the declaration,
' not the identifier.
If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then
node = node.Parent
End If
Return node
End Function
Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode
Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind)
' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause.
If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then
Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax)
Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax)
If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then
Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode)
End If
End If
Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode)
End Function
Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsClosureScope(node)
End Function
Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode
Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt)
While node IsNot root And node IsNot Nothing
Dim body As SyntaxNode = Nothing
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then
Return body
End If
node = node.Parent
End While
Return Nothing
End Function
Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda)
End Function
Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode)
Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit)
End Function
Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode)
Contract.ThrowIfNull(oldDeclaration.Parent)
Contract.ThrowIfNull(newDeclaration.Parent)
' Allow matching field declarations represented by a identitifer and the whole variable declarator
' even when their node kinds do not match.
If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then
oldDeclaration = oldDeclaration.Parent
ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then
newDeclaration = newDeclaration.Parent
End If
Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration})
Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent)
End Function
Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode)
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then
' The root is a single/multi line sub/function lambda.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
If TypeOf oldBody Is ExpressionSyntax Then
' Dim a = <Expression>
' Dim a As <NewExpression>
' Dim a, b, c As <NewExpression>
' Queries: The root is a query clause, the body is the expression.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root.
' The body of an array initialized fields is an ArgumentListSyntax, which is the match root.
Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches)
End Function
Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode,
statementPart As Integer,
oldBody As SyntaxNode,
newBody As SyntaxNode,
<Out> ByRef newStatement As SyntaxNode) As Boolean
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
' only statements in bodies of the same kind can be matched
Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax))
Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
' methods
If TypeOf oldBody Is MethodBlockBaseSyntax Then
newStatement = Nothing
Return False
End If
' lambdas
If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then
Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax)
Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax)
If oldSingleLineLambda IsNot Nothing AndAlso
newSingleLineLambda IsNot Nothing AndAlso
oldStatement Is oldSingleLineLambda.Body Then
newStatement = newSingleLineLambda.Body
Return True
End If
newStatement = Nothing
Return False
End If
' array initialized fields
If newBody.IsKind(SyntaxKind.ArgumentList) Then
' the parent ModifiedIdentifier is the active statement
If oldStatement Is oldBody.Parent Then
newStatement = newBody.Parent
Return True
End If
newStatement = Nothing
Return False
End If
' field and property initializers
If TypeOf newBody Is ExpressionSyntax Then
If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
' field
Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax)
Dim oldName As SyntaxToken
If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then
oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier
Else
oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier
End If
For Each newName In newDeclarator.Names
If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then
newStatement = newName
Return True
End If
Next
newStatement = Nothing
Return False
ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' property
If oldStatement Is oldBody.Parent.Parent Then
newStatement = newBody.Parent.Parent
Return True
End If
newStatement = newBody
Return True
End If
End If
' queries
If oldStatement Is oldBody Then
newStatement = newBody
Return True
End If
newStatement = Nothing
Return False
End Function
#End Region
#Region "Syntax And Semantic Utils"
Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan
Return Nothing
End Function
Protected Overrides ReadOnly Property LineDirectiveKeyword As String
Get
Return "ExternalSource"
End Get
End Property
Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort
Get
Return SyntaxKind.ExternalSourceDirectiveTrivia
End Get
End Property
Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit)
Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes)
End Function
Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode
Get
Return SyntaxFactory.CompilationUnit()
End Get
End Property
Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean
' There are no experimental features at this time.
Return False
End Function
Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean
Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2)
End Function
Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean
Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression)
End Function
Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span)
End Function
Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span)
End Function
Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer))
Dim direction As Integer = +1
Dim nodeOrToken As SyntaxNodeOrToken = statement
Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement)
While True
' If the current statement is the last statement of if-block or try-block statements
' pretend there are no siblings following it.
Dim lastBlockStatement As SyntaxNode = Nothing
If nodeOrToken.Parent IsNot Nothing Then
If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault()
End If
End If
If direction > 0 Then
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
Else
nodeOrToken = nodeOrToken.GetNextSibling()
End If
Else
nodeOrToken = nodeOrToken.GetPreviousSibling()
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
End If
End If
If nodeOrToken.RawKind = 0 Then
Dim parent = statement.Parent
If parent Is Nothing Then
Return
End If
If direction > 0 Then
nodeOrToken = statement
direction = -1
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Yield (statement, -1)
End If
nodeOrToken = parent
statement = parent
propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement)
direction = +1
End If
Dim node = nodeOrToken.AsNode()
If node Is Nothing Then
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Dim nodeModifiers = GetFieldOrPropertyModifiers(node)
If Not nodeModifiers.HasValue OrElse
propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then
Continue While
End If
End If
Yield (node, DefaultStatementPart)
End While
End Function
Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList?
If node.IsKind(SyntaxKind.FieldDeclaration) Then
Return DirectCast(node, FieldDeclarationSyntax).Modifiers
ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then
Return DirectCast(node, PropertyStatementSyntax).Modifiers
Else
Return Nothing
End If
End Function
Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean
Return SyntaxFactory.AreEquivalent(left, right)
End Function
Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean
' usual case
If SyntaxFactory.AreEquivalent(left, right) Then
Return True
End If
Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right)
End Function
Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean
If oldStatement.RawKind <> newStatement.RawKind Then
Return False
End If
' Dim a,b,c As <NewExpression>
' We need to check the actual initializer expression in addition to the identifier.
If HasMultiInitializer(oldStatement) Then
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso
AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause,
DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause)
End If
Select Case oldStatement.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Header statements are nops. Changes in the header statements are changes in top-level surface
' which should not be reported as active statement rude edits.
Return True
Case Else
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement)
End Select
End Function
Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean
Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.InterfaceBlock)
End Function
Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean
' No records in VB
Return False
End Function
Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode
Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock?
End Function
Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then
Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList))
declaration = node.Parent.Parent
Return True
End If
If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then
declaration = node.Parent
Return True
End If
declaration = Nothing
Return False
End Function
Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean
Return SyntaxUtilities.HasBackingField(propertyDeclaration)
End Function
Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax)
Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse
declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing)
Case SyntaxKind.ModifiedIdentifier
Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
declaration.Parent.IsKind(SyntaxKind.Parameter))
If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
Return False
End If
Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax)
Return identifier.ArrayBounds IsNot Nothing OrElse
GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing
Case Else
Return False
End Select
End Function
Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean
Return False
End Function
Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax
If equalsValue IsNot Nothing Then
Return equalsValue.Value
End If
If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then
Return DirectCast(asClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
End Function
''' <summary>
''' VB symbols return references that represent the declaration statement.
''' The node that represenets the whole declaration (the block) is the parent node if it exists.
''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body
''' is represented by its declaration statement.
''' </summary>
Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode
Dim syntax = reference.GetSyntax(cancellationToken)
Dim parent = syntax.Parent
Select Case syntax.Kind
' declarations that always have block
Case SyntaxKind.NamespaceStatement
Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock)
Return parent
Case SyntaxKind.ClassStatement
Debug.Assert(parent.Kind = SyntaxKind.ClassBlock)
Return parent
Case SyntaxKind.StructureStatement
Debug.Assert(parent.Kind = SyntaxKind.StructureBlock)
Return parent
Case SyntaxKind.InterfaceStatement
Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock)
Return parent
Case SyntaxKind.ModuleStatement
Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock)
Return parent
Case SyntaxKind.EnumStatement
Debug.Assert(parent.Kind = SyntaxKind.EnumBlock)
Return parent
Case SyntaxKind.SubNewStatement
Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock)
Return parent
Case SyntaxKind.OperatorStatement
Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock)
Return parent
Case SyntaxKind.GetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock)
Return parent
Case SyntaxKind.SetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock)
Return parent
Case SyntaxKind.AddHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock)
Return parent
Case SyntaxKind.RemoveHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock)
Return parent
Case SyntaxKind.RaiseEventAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock)
Return parent
' declarations that may or may not have block
Case SyntaxKind.SubStatement
Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax)
Case SyntaxKind.FunctionStatement
Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax)
Case SyntaxKind.PropertyStatement
Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax)
Case SyntaxKind.EventStatement
Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax)
' declarations that never have a block
Case SyntaxKind.ModifiedIdentifier
Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax)
Return If(variableDeclaration.Names.Count = 1, parent, syntax)
Case SyntaxKind.VariableDeclarator
' fields are represented by ModifiedIdentifier:
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
Case Else
Return syntax
End Select
End Function
Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean
Dim ctor = TryCast(declaration, ConstructorBlockSyntax)
If ctor Is Nothing Then
Return False
End If
' Constructor includes field initializers if the first statement
' isn't a call to another constructor of the declaring class or module.
If ctor.Statements.Count = 0 Then
Return True
End If
Dim firstStatement = ctor.Statements.First
If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then
Return True
End If
Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax)
If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then
Return True
End If
Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return True
End If
Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse
Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then
Return True
End If
' Note that ValueText returns "New" for both New and [New]
If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword)
End Function
Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean
Dim syntaxRefs = type.DeclaringSyntaxReferences
Return syntaxRefs.Length > 1 OrElse
DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword)
End Function
Protected Overrides Function GetSymbolEdits(
editKind As EditKind,
oldNode As SyntaxNode,
newNode As SyntaxNode,
oldModel As SemanticModel,
newModel As SemanticModel,
editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind),
cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind))
Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing
Dim newSymbols As OneOrMany(Of ISymbol) = Nothing
If editKind = EditKind.Delete Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind))
End If
If editKind = EditKind.Insert Then
If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind))
End If
If editKind = EditKind.Update Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse
Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then
Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind))
End If
' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list,
' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits,
' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields.
Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance()
For Each oldSymbol In oldSymbols
Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol)
If newSymbol IsNot Nothing Then
builder.Add((oldSymbol, newSymbol, editKind))
End If
Next
Return OneOrMany.Create(builder.ToImmutableAndFree())
End If
Throw ExceptionUtilities.UnexpectedValue(editKind)
End Function
Private Shared Function TryGetSyntaxNodesForEdit(
editKind As EditKind,
node As SyntaxNode,
model As SemanticModel,
<Out> ByRef symbols As OneOrMany(Of ISymbol),
cancellationToken As CancellationToken) As Boolean
Select Case node.Kind()
Case SyntaxKind.ImportsStatement,
SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock
Return False
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = CType(node, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken)))
Return True
End If
node = variableDeclarator.Names(0)
Case SyntaxKind.FieldDeclaration
If editKind = EditKind.Update Then
Dim field = CType(node, FieldDeclarationSyntax)
If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then
node = field.Declarators(0).Names(0)
Else
symbols = OneOrMany.Create(
(From declarator In field.Declarators
From name In declarator.Names
Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray())
Return True
End If
End If
End Select
Dim symbol = model.GetDeclaredSymbol(node, cancellationToken)
If symbol Is Nothing Then
Return False
End If
' Ignore partial method definition parts.
' Partial method that does not have implementation part is not emitted to metadata.
' Partial method without a definition part is a compilation error.
If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then
Return False
End If
symbols = OneOrMany.Create(symbol)
Return True
End Function
Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean
Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda)
End Function
Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsLambda(node)
End Function
Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax
End Function
Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean
Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2)
End Function
Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetLambda(lambdaBody)
End Function
Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody)
End Function
Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol
Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax)
' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header)
Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol)
End Function
Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode
Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax)
End Function
Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.AggregateClause
Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol)
Case SyntaxKind.CollectionRangeVariable
Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol)
Case SyntaxKind.FunctionAggregation
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.ExpressionRangeVariable
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.FromClause,
SyntaxKind.WhereClause,
SyntaxKind.SkipClause,
SyntaxKind.TakeClause,
SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause,
SyntaxKind.SelectClause
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case Else
Return True
End Select
End Function
Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode))
' VB has no local functions so we don't have anything to report
End Sub
#End Region
#Region "Diagnostic Info"
Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat
Get
Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat
End Get
End Property
Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span)
End Function
Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind)
End Function
Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return GetDiagnosticSpan(node, editKind)
End Function
' internal for testing; kind is passed explicitly for testing as well
Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan?
Select Case kind
Case SyntaxKind.CompilationUnit
Return New TextSpan()
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement
Return node.Span
Case SyntaxKind.NamespaceBlock
Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement)
Case SyntaxKind.NamespaceStatement
Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax))
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock
Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement)
Case SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement
Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax))
Case SyntaxKind.EnumBlock
Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind)
Case SyntaxKind.EnumStatement
Dim enumStatement = DirectCast(node, EnumStatementSyntax)
Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement)
Case SyntaxKind.EventBlock
Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.EventStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.PropertyBlock
Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement)
Case SyntaxKind.PropertyStatement
Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax))
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last)
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return node.Span
Case SyntaxKind.TypeParameter
Return DirectCast(node, TypeParameterSyntax).Identifier.Span
Case SyntaxKind.TypeParameterList,
SyntaxKind.ParameterList,
SyntaxKind.AttributeList,
SyntaxKind.SimpleAsClause
If editKind = EditKind.Delete Then
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Else
Return node.Span
End If
Case SyntaxKind.AttributesStatement,
SyntaxKind.Attribute
Return node.Span
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader)
Case SyntaxKind.MultiLineIfBlock
Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.ElseIfBlock
Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement
Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword)
Case SyntaxKind.SingleLineIfStatement
Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax)
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement.Span
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span
Case SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock,
SyntaxKind.DoLoopUntilBlock
Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span
Case SyntaxKind.ForEachBlock,
SyntaxKind.ForBlock
Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span
Case SyntaxKind.AwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span
Case SyntaxKind.AnonymousObjectCreationExpression
Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax)
Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start,
newWith.Initializer.WithKeyword.Span.End)
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span
Case SyntaxKind.QueryExpression
Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind)
Case SyntaxKind.WhereClause
Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span
Case SyntaxKind.SelectClause
Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span
Case SyntaxKind.FromClause
Return DirectCast(node, FromClauseSyntax).FromKeyword.Span
Case SyntaxKind.AggregateClause
Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span
Case SyntaxKind.LetClause
Return DirectCast(node, LetClauseSyntax).LetKeyword.Span
Case SyntaxKind.SimpleJoinClause
Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span
Case SyntaxKind.GroupJoinClause
Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax)
Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End)
Case SyntaxKind.GroupByClause
Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span
Case SyntaxKind.FunctionAggregation
Return node.Span
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause,
SyntaxKind.SkipWhileClause
Dim partition = DirectCast(node, PartitionWhileClauseSyntax)
Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return node.Span
Case SyntaxKind.JoinCondition
Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span
Case Else
Return node.Span
End Select
End Function
Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan
Return TextSpan.FromBounds(ifKeyword.Span.Start,
If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End))
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan
Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan
Return GetDiagnosticSpan(node.Modifiers,
node.DeclarationKeyword,
If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken)))
End Function
Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan
Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart),
endNode.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan
Dim startToken As SyntaxToken
Dim endToken As SyntaxToken
If header.Modifiers.Count > 0 Then
startToken = header.Modifiers.First
Else
Select Case header.Kind
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword
Case Else
startToken = header.DeclarationKeyword
End Select
End If
If header.ParameterList IsNot Nothing Then
endToken = header.ParameterList.CloseParenToken
Else
Select Case header.Kind
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
endToken = DirectCast(header, MethodStatementSyntax).Identifier
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token
Case SyntaxKind.OperatorStatement
endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken
Case SyntaxKind.SubNewStatement
endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword
Case SyntaxKind.PropertyStatement
endToken = DirectCast(header, PropertyStatementSyntax).Identifier
Case SyntaxKind.EventStatement
endToken = DirectCast(header, EventStatementSyntax).Identifier
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
endToken = DirectCast(header, DelegateStatementSyntax).Identifier
Case SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
endToken = header.DeclarationKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(header.Kind)
End Select
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan
Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword)
Dim endToken As SyntaxToken
If lambda.ParameterList IsNot Nothing Then
endToken = lambda.ParameterList.CloseParenToken
Else
endToken = lambda.DeclarationKeyword
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan
Select Case lambda.Kind
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span
Case Else
Return lambda.Span
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String
Select Case symbol.TypeKind
Case TypeKind.Structure
Return VBFeaturesResources.structure_
Case TypeKind.Module
Return VBFeaturesResources.module_
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String
Select Case symbol.MethodKind
Case MethodKind.StaticConstructor
Return VBFeaturesResources.Shared_constructor
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String
If symbol.IsWithEvents Then
Return VBFeaturesResources.WithEvents_field
End If
Return MyBase.GetDisplayName(symbol)
End Function
Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Return TryGetDisplayNameImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Dim result = TryGetDisplayNameImpl(node, editKind)
If result Is Nothing Then
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End If
Return result
End Function
Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String
Return GetDisplayName(node, editKind)
End Function
Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String
Select Case node.Kind
' top-level
Case SyntaxKind.OptionStatement
Return VBFeaturesResources.option_
Case SyntaxKind.ImportsStatement
Return VBFeaturesResources.import
Case SyntaxKind.NamespaceBlock,
SyntaxKind.NamespaceStatement
Return FeaturesResources.namespace_
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement
Return FeaturesResources.class_
Case SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement
Return VBFeaturesResources.structure_
Case SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement
Return FeaturesResources.interface_
Case SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement
Return VBFeaturesResources.module_
Case SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement
Return FeaturesResources.enum_
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return FeaturesResources.delegate_
Case SyntaxKind.FieldDeclaration
Dim declaration = DirectCast(node, FieldDeclarationSyntax)
Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field,
If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field))
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return FeaturesResources.method
Case SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement
Return FeaturesResources.operator_
Case SyntaxKind.ConstructorBlock
Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.SubNewStatement
Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.PropertyBlock
Return FeaturesResources.property_
Case SyntaxKind.PropertyStatement
Return If(node.IsParentKind(SyntaxKind.PropertyBlock),
FeaturesResources.property_,
FeaturesResources.auto_property)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return FeaturesResources.event_
Case SyntaxKind.EnumMemberDeclaration
Return FeaturesResources.enum_value
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
Return FeaturesResources.property_accessor
Case SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return FeaturesResources.event_accessor
Case SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return FeaturesResources.type_constraint
Case SyntaxKind.SimpleAsClause
Return VBFeaturesResources.as_clause
Case SyntaxKind.TypeParameterList
Return VBFeaturesResources.type_parameters
Case SyntaxKind.TypeParameter
Return FeaturesResources.type_parameter
Case SyntaxKind.ParameterList
Return VBFeaturesResources.parameters
Case SyntaxKind.Parameter
Return FeaturesResources.parameter
Case SyntaxKind.AttributeList,
SyntaxKind.AttributesStatement
Return VBFeaturesResources.attributes
Case SyntaxKind.Attribute
Return FeaturesResources.attribute
' statement-level
Case SyntaxKind.TryBlock
Return VBFeaturesResources.Try_block
Case SyntaxKind.CatchBlock
Return VBFeaturesResources.Catch_clause
Case SyntaxKind.FinallyBlock
Return VBFeaturesResources.Finally_clause
Case SyntaxKind.UsingBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block)
Case SyntaxKind.WithBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block)
Case SyntaxKind.SyncLockBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block)
Case SyntaxKind.ForEachBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block)
Case SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.OnErrorGoToLabelStatement
Return VBFeaturesResources.On_Error_statement
Case SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return VBFeaturesResources.Resume_statement
Case SyntaxKind.YieldStatement
Return VBFeaturesResources.Yield_statement
Case SyntaxKind.AwaitExpression
Return VBFeaturesResources.Await_expression
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return VBFeaturesResources.Lambda
Case SyntaxKind.WhereClause
Return VBFeaturesResources.Where_clause
Case SyntaxKind.SelectClause
Return VBFeaturesResources.Select_clause
Case SyntaxKind.FromClause
Return VBFeaturesResources.From_clause
Case SyntaxKind.AggregateClause
Return VBFeaturesResources.Aggregate_clause
Case SyntaxKind.LetClause
Return VBFeaturesResources.Let_clause
Case SyntaxKind.SimpleJoinClause
Return VBFeaturesResources.Join_clause
Case SyntaxKind.GroupJoinClause
Return VBFeaturesResources.Group_Join_clause
Case SyntaxKind.GroupByClause
Return VBFeaturesResources.Group_By_clause
Case SyntaxKind.FunctionAggregation
Return VBFeaturesResources.Function_aggregation
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause
Return VBFeaturesResources.Take_While_clause
Case SyntaxKind.SkipWhileClause
Return VBFeaturesResources.Skip_While_clause
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return VBFeaturesResources.Ordering_clause
Case SyntaxKind.JoinCondition
Return VBFeaturesResources.Join_condition
Case Else
Return Nothing
End Select
End Function
#End Region
#Region "Top-level Syntactic Rude Edits"
Private Structure EditClassifier
Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer
Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic)
Private ReadOnly _match As Match(Of SyntaxNode)
Private ReadOnly _oldNode As SyntaxNode
Private ReadOnly _newNode As SyntaxNode
Private ReadOnly _kind As EditKind
Private ReadOnly _span As TextSpan?
Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer,
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
oldNode As SyntaxNode,
newNode As SyntaxNode,
kind As EditKind,
Optional match As Match(Of SyntaxNode) = Nothing,
Optional span As TextSpan? = Nothing)
_analyzer = analyzer
_diagnostics = diagnostics
_oldNode = oldNode
_newNode = newNode
_kind = kind
_span = span
_match = match
End Sub
Private Sub ReportError(kind As RudeEditKind)
ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)})
End Sub
Private Sub ReportError(kind As RudeEditKind, args As String())
_diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args))
End Sub
Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode)
_diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)}))
End Sub
Private Function GetSpan() As TextSpan
If _span.HasValue Then
Return _span.Value
End If
If _newNode Is Nothing Then
Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode)
Else
Return GetDiagnosticSpan(_newNode, _kind)
End If
End Function
Public Sub ClassifyEdit()
Select Case _kind
Case EditKind.Delete
ClassifyDelete(_oldNode)
Return
Case EditKind.Update
ClassifyUpdate(_oldNode, _newNode)
Return
Case EditKind.Move
ClassifyMove(_newNode)
Return
Case EditKind.Insert
ClassifyInsert(_newNode)
Return
Case EditKind.Reorder
ClassifyReorder(_oldNode, _newNode)
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(_kind)
End Select
End Sub
#Region "Move and Reorder"
Private Sub ClassifyMove(newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
ReportError(RudeEditKind.Move)
End Select
End Sub
Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint,
SyntaxKind.AttributeList,
SyntaxKind.Attribute
' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
Return
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
' Interface methods. We could allow reordering of non-COM interface methods.
Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock))
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.PropertyStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.EventStatement
' Maybe we could allow changing order of field declarations unless the containing type layout is sequential,
' and it's not a COM interface.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.EnumMemberDeclaration
' To allow this change we would need to check that values of all fields of the enum
' are preserved, or make sure we can update all method bodies that accessed those that changed.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.TypeParameter,
SyntaxKind.Parameter
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(newNode.Kind)
End Select
End Sub
#End Region
#Region "Insert"
Private Sub ClassifyInsert(node As SyntaxNode)
Select Case node.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.AttributesStatement
' Module/assembly attribute
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude
If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude
If node.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Delete"
Private Sub ClassifyDelete(oldNode As SyntaxNode)
Select Case oldNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Delete)
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude edits
If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Update"
Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.NamespaceStatement
ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax))
Return
Case SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Update)
End If
Return
End Select
End Sub
Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax)
Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
ReportError(RudeEditKind.Renamed)
End Sub
Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode)
For Each node In newDeclarationOrBody.DescendantNodesAndSelf()
Select Case node.Kind
Case SyntaxKind.AggregateClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode)
Return
Case SyntaxKind.LocalDeclarationStatement
Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax)
If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then
ReportError(RudeEditKind.UpdateStaticLocal)
End If
End Select
Next
End Sub
#End Region
End Structure
Friend Overrides Sub ReportTopLevelSyntacticRudeEdits(
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
edit As Edit(Of SyntaxNode),
editMap As Dictionary(Of SyntaxNode, EditKind))
' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively.
' For ModifiedIdentifiers though we check the grandparent instead because variables can move across
' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in
' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator.
If edit.Kind = EditKind.Delete AndAlso
edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then
Return
End If
ElseIf edit.Kind = EditKind.Insert AndAlso
edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then
Return
End If
ElseIf HasParentEdit(editMap, edit) Then
Return
End If
Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match)
classifier.ClassifyEdit()
End Sub
Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?)
Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span)
classifier.ClassifyDeclarationBodyRudeUpdates(newMember)
End Sub
#End Region
#Region "Semantic Rude Edits"
Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean
Return oldMethod.HandledEvents.SequenceEqual(
newMethod.HandledEvents,
Function(x, y)
Return x.HandlesKind = y.HandlesKind AndAlso
SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso
SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso
SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty)
End Function)
End Function
Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean)
Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType)
If kind <> RudeEditKind.None Then
diagnostics.Add(New RudeEditDiagnostic(
kind,
GetDiagnosticSpan(newNode, EditKind.Insert),
newNode,
arguments:={GetDisplayName(newNode, EditKind.Insert)}))
End If
End Sub
Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting P/Invoke into a new or existing type is not allowed.
If method.GetDllImportData() IsNot Nothing Then
Return RudeEditKind.InsertDllImport
End If
' Inserting method with handles clause into a new or existing type is not allowed.
If Not method.HandledEvents.IsEmpty Then
Return RudeEditKind.InsertHandlesClause
End If
Case SymbolKind.NamedType
Dim type = CType(newSymbol, INamedTypeSymbol)
' Inserting module is not allowed.
If type.TypeKind = TypeKind.Module Then
Return RudeEditKind.Insert
End If
End Select
' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted):
If Not insertingIntoExistingContainingType Then
Return RudeEditKind.None
End If
If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertIntoGenericType
End If
' Inserting virtual or interface member is not allowed.
If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertVirtual
End If
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting generic method into an existing type is not allowed.
If method.Arity > 0 Then
Return RudeEditKind.InsertGenericMethod
End If
' Inserting operator to an existing type is not allowed.
If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then
Return RudeEditKind.InsertOperator
End If
Return RudeEditKind.None
Case SymbolKind.Field
' Inserting a field into an enum is not allowed.
If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then
Return RudeEditKind.Insert
End If
Return RudeEditKind.None
End Select
Return RudeEditKind.None
End Function
#End Region
#Region "Exception Handling Rude Edits"
Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)()
While node IsNot Nothing
Dim kind = node.Kind
Select Case kind
Case SyntaxKind.TryBlock
If isNonLeaf Then
result.Add(node)
End If
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
result.Add(node)
Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock)
node = node.Parent
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock
' stop at type declaration
Exit While
End Select
' stop at lambda
If LambdaUtilities.IsLambda(node) Then
Exit While
End If
node = node.Parent
End While
Return result
End Function
Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)),
oldStatement As SyntaxNode,
newStatementSpan As TextSpan)
For Each edit In exceptionHandlingEdits
Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind)
If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan)
End If
Next
End Sub
Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.TryBlock
Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax)
Dim newTryBlock = DirectCast(newNode, TryBlockSyntax)
Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso
SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks)
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
Return SyntaxFactory.AreEquivalent(oldNode, newNode)
Case Else
Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind)
End Select
End Function
''' <summary>
''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly.
''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only.
''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only.
''' </summary>
Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan
Select Case node.Kind
Case SyntaxKind.TryBlock
Dim tryBlock = DirectCast(node, TryBlockSyntax)
coversAllChildren = False
If tryBlock.CatchBlocks.Count = 0 Then
Debug.Assert(tryBlock.FinallyBlock IsNot Nothing)
Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End)
End If
Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End)
Case SyntaxKind.CatchBlock
coversAllChildren = True
Return node.Span
Case SyntaxKind.FinallyBlock
coversAllChildren = True
Return DirectCast(node.Parent, TryBlockSyntax).Span
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
#End Region
#Region "State Machines"
Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean
Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse
SyntaxUtilities.IsIteratorMethodOrLambda(declaration)
End Function
Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds)
' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#)
If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body)
kind = StateMachineKinds.Async
ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetYieldStatements(body)
kind = StateMachineKinds.Iterator
Else
suspensionPoints = ImmutableArray(Of SyntaxNode).Empty
kind = StateMachineKinds.None
End If
End Sub
Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode)
' TODO: changes around suspension points (foreach, lock, using, etc.)
If newNode.IsKind(SyntaxKind.AwaitExpression) Then
Dim oldContainingStatementPart = FindContainingStatementPart(oldNode)
Dim newContainingStatementPart = FindContainingStatementPart(newNode)
' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state.
If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso
Not HasNoSpilledState(newNode, newContainingStatementPart) Then
diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span))
End If
End If
End Sub
Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode
Dim statement = TryCast(node, StatementSyntax)
While statement Is Nothing
Select Case node.Parent.Kind()
Case SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.IfStatement,
SyntaxKind.WhileStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SelectStatement,
SyntaxKind.UsingStatement
Return node
End Select
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then
Return node
End If
node = node.Parent
statement = TryCast(node, StatementSyntax)
End While
Return statement
End Function
Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean
Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression))
' There is nothing within the statement part surrounding the await expression.
If containingStatementPart Is awaitExpression Then
Return True
End If
Select Case containingStatementPart.Kind()
Case SyntaxKind.ExpressionStatement,
SyntaxKind.ReturnStatement
Dim expression = GetExpressionFromStatementPart(containingStatementPart)
' Await <expr>
' Return Await <expr>
If expression Is awaitExpression Then
Return True
End If
' <ident> = Await <expr>
' Return <ident> = Await <expr>
Return IsSimpleAwaitAssignment(expression, awaitExpression)
Case SyntaxKind.VariableDeclarator
' <ident> = Await <expr> in using, for, etc
' EqualsValue -> VariableDeclarator
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement
' Until Await <expr>
' UntilClause -> LoopUntilStatement
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LocalDeclarationStatement
' Dim <ident> = Await <expr>
' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement
Return awaitExpression.Parent.Parent.Parent Is containingStatementPart
End Select
Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression)
End Function
Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax
Select Case statement.Kind()
Case SyntaxKind.ExpressionStatement
Return DirectCast(statement, ExpressionStatementSyntax).Expression
Case SyntaxKind.ReturnStatement
Return DirectCast(statement, ReturnStatementSyntax).Expression
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind())
End Select
End Function
Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignment = DirectCast(node, AssignmentStatementSyntax)
Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression
End If
Return False
End Function
#End Region
#Region "Rude Edits around Active Statement"
Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode,
isNonLeaf As Boolean)
Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot)
If onErrorOrResumeStatement IsNot Nothing Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span)
End If
ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement)
End Sub
Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode
For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody)
Select Case node.Kind
Case SyntaxKind.OnErrorGoToLabelStatement,
SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return node
End Select
Next
Return Nothing
End Function
Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode)
' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement.
' Although such changes are technically possible, they might lead to confusion since
' the temporary variables these statements generate won't be properly initialized.
'
' We use a simple algorithm to match each New node with its old counterpart.
' If all nodes match this algorithm Is linear, otherwise it's quadratic.
'
' Unlike exception regions matching where we use LCS, we allow reordering of the statements.
ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement),
areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable,
DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable))
End Sub
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer
Inherits AbstractEditAndContinueAnalyzer
<ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]>
Private NotInheritable Class Factory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing)
End Function
End Class
' Public for testing purposes
Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing)
MyBase.New(testFaultInjector)
End Sub
#Region "Syntax Analysis"
Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean
Dim current = node
While current IsNot rootOpt
Select Case current.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
declarations = OneOrMany.Create(current)
Return True
Case SyntaxKind.PropertyStatement
' Property a As Integer = 1
' Property a As New T
If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then
declarations = OneOrMany.Create(current)
Return True
End If
Case SyntaxKind.VariableDeclarator
If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Dim variableDeclarator = CType(current, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count = 1 Then
declarations = OneOrMany.Create(current)
Else
declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode)))
End If
Return True
End If
Case SyntaxKind.ModifiedIdentifier
If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
declarations = OneOrMany.Create(current)
Return True
End If
End Select
current = current.Parent
End While
declarations = Nothing
Return False
End Function
''' <summary>
''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean
Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
''' <summary>
''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean
Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1
End Function
''' <returns>
''' Given a node representing a declaration or a top-level edit node returns:
''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors.
''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause.
''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer".
''' A null reference otherwise.
''' </returns>
Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node
Case SyntaxKind.PropertyStatement
' the body is the initializer expression/new expression (if any)
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return propertyStatement.Initializer.Value
End If
If HasAsNewClause(propertyStatement) Then
Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
Dim body As SyntaxNode = Nothing
If variableDeclarator.Initializer IsNot Nothing Then
' Dim a = initializer
body = variableDeclarator.Initializer.Value
ElseIf HasAsNewClause(variableDeclarator) Then
' Dim a As New T
' Dim a,b As New T
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As T
If variableDeclarator.Names.Count = 1 Then
Dim name = variableDeclarator.Names(0)
If name.ArrayBounds IsNot Nothing Then
' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, name.ArrayBounds, Nothing)
End If
End If
Return body
Case SyntaxKind.ModifiedIdentifier
If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax)
Dim body As SyntaxNode = Nothing
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing)
End If
Return body
Case Else
' Note: A method without body is represented by a SubStatement.
Return Nothing
End Select
End Function
Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean
If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then
Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax)
Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator)
End If
Return False
End Function
Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol)
Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
If methodBlock.Statements.IsEmpty Then
Return ImmutableArray(Of ISymbol).Empty
End If
Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured
End If
Dim expression = TryCast(memberBody, ExpressionSyntax)
If expression IsNot Nothing Then
Return model.AnalyzeDataFlow(expression).Captured
End If
' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me".
' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer
Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax)
If arrayBounds IsNot Nothing Then
Return ImmutableArray.CreateRange(
arrayBounds.Arguments.
SelectMany(AddressOf GetArgumentExpressions).
SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured).
Distinct())
End If
Throw ExceptionUtilities.UnexpectedValue(memberBody)
End Function
Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax)
Select Case argument.Kind
Case SyntaxKind.SimpleArgument
Yield DirectCast(argument, SimpleArgumentSyntax).Expression
Case SyntaxKind.RangeArgument
Dim range = DirectCast(argument, RangeArgumentSyntax)
Yield range.LowerBound
Yield range.UpperBound
Case SyntaxKind.OmittedArgument
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
End Function
Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean
Return False
End Function
Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode)
Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol)
' Not supported (it's non trivial to find all places where "this" is used):
Debug.Assert(Not localOrParameter.IsThisParameter())
Return From root In roots
From node In root.DescendantNodesAndSelf()
Where node.IsKind(SyntaxKind.IdentifierName)
Let identifier = DirectCast(node, IdentifierNameSyntax)
Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso
If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False)
Select node
End Function
Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean
Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
''' <returns>
''' Methods, operators, constructors, property and event accessors:
''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans.
''' Field declarations in form of "Dim a, b, c As New C()"
''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas.
''' For simplicity we don't allow moving the new expression independently of the field name.
''' Field declarations with array initializers "Dim a(n), b(n) As Integer"
''' - Breakpoint spans cover "a(n)" and "b(n)".
''' </returns>
Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken)
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node.DescendantTokens()
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(),
Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens())
End If
If HasAsNewClause(propertyStatement) Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens())
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If Not IsFieldDeclaration(variableDeclarator) Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
If Not IsFieldDeclaration(modifiedIdentifier) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens())
End If
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return node.DescendantTokens()
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan)
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return (declaration.Span, Nothing)
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing)
End If
If HasAsNewClause(propertyStatement) Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing)
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax)
If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax)
Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End),
hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start))
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax)
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (declaration.Span, Nothing)
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode
' AsNewClause is a match root for field/property As New initializer
' EqualsClause is a match root for field/property initializer
If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement))
Return bodyOrMatchRoot.Parent
End If
' ArgumentList is a match root for an array initialized field
If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return bodyOrMatchRoot.Parent
End If
' The following active nodes are outside of the initializer body,
' we need to return a node that encompasses them.
' Dim [|a = <<Body>>|]
' Dim [|a As Integer = <<Body>>|]
' Dim [|a As <<Body>>|]
' Dim [|a|], [|b|], [|c|] As <<Body>>
' Property [|P As Integer = <<Body>>|]
' Property [|P As <<Body>>|]
If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then
Return bodyOrMatchRoot.Parent.Parent
End If
Return bodyOrMatchRoot
End Function
Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode,
span As TextSpan,
partnerDeclarationBodyOpt As SyntaxNode,
<Out> ByRef partnerOpt As SyntaxNode,
<Out> ByRef statementPart As Integer) As SyntaxNode
Dim position = span.Start
SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False)
Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind)
' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>.
' Simple field initializers: Dim [|a = <<expr>>|]
' Dim [|a As Integer = <<expr>>|]
' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|]
' Dim [|a As <<New C>>|]
' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer
' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>>
' Property initializers: Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If position < declarationBody.SpanStart Then
If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
Return declarationBody.Parent.Parent
End If
If declarationBody.IsKind(SyntaxKind.ArgumentList) Then
' Dim a<<ArgumentList>> As Integer
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent
End If
Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return declarationBody.Parent
End If
If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then
Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
' Dim a, b, c As <<NewExpression>>
Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position)
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex)
End If
Return variableDeclarator.Names(nameIndex)
Else
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
' Dim a As <<NewExpression>>
Return variableDeclarator
End If
End If
If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Return declarationBody.Parent.Parent
End If
End If
If Not declarationBody.FullSpan.Contains(position) Then
' invalid position, let's find a labeled node that encompasses the body:
position = declarationBody.SpanStart
End If
Dim node As SyntaxNode = Nothing
If partnerDeclarationBodyOpt IsNot Nothing Then
SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt)
Else
node = declarationBody.FindToken(position).Parent
partnerOpt = Nothing
End If
' In some cases active statements may start at the same position.
' Consider a nested lambda:
' Function(a) [|[|Function(b)|] a + b|]
' There are 2 active statements, one spanning the the body of the outer lambda and
' the other on the nested lambda's header.
' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length.
While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position
node = node.Parent
partnerOpt = partnerOpt?.Parent
End While
Debug.Assert(node IsNot Nothing)
While node IsNot declarationBody AndAlso
Not SyntaxComparer.Statement.HasLabel(node) AndAlso
Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node)
node = node.Parent
If partnerOpt IsNot Nothing Then
partnerOpt = partnerOpt.Parent
End If
End While
' In case of local variable declaration an active statement may start with a modified identifier.
' If it is a declaration with a simple initializer we want the resulting statement to be the declaration,
' not the identifier.
If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then
node = node.Parent
End If
Return node
End Function
Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode
Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind)
' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause.
If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then
Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax)
Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax)
If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then
Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode)
End If
End If
Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode)
End Function
Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsClosureScope(node)
End Function
Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode
Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt)
While node IsNot root And node IsNot Nothing
Dim body As SyntaxNode = Nothing
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then
Return body
End If
node = node.Parent
End While
Return Nothing
End Function
Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda)
End Function
Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode)
Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit)
End Function
Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode)
Contract.ThrowIfNull(oldDeclaration.Parent)
Contract.ThrowIfNull(newDeclaration.Parent)
' Allow matching field declarations represented by a identitifer and the whole variable declarator
' even when their node kinds do not match.
If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then
oldDeclaration = oldDeclaration.Parent
ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then
newDeclaration = newDeclaration.Parent
End If
Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration})
Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent)
End Function
Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode)
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then
' The root is a single/multi line sub/function lambda.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
If TypeOf oldBody Is ExpressionSyntax Then
' Dim a = <Expression>
' Dim a As <NewExpression>
' Dim a, b, c As <NewExpression>
' Queries: The root is a query clause, the body is the expression.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root.
' The body of an array initialized fields is an ArgumentListSyntax, which is the match root.
Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches)
End Function
Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode,
statementPart As Integer,
oldBody As SyntaxNode,
newBody As SyntaxNode,
<Out> ByRef newStatement As SyntaxNode) As Boolean
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
' only statements in bodies of the same kind can be matched
Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax))
Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
' methods
If TypeOf oldBody Is MethodBlockBaseSyntax Then
newStatement = Nothing
Return False
End If
' lambdas
If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then
Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax)
Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax)
If oldSingleLineLambda IsNot Nothing AndAlso
newSingleLineLambda IsNot Nothing AndAlso
oldStatement Is oldSingleLineLambda.Body Then
newStatement = newSingleLineLambda.Body
Return True
End If
newStatement = Nothing
Return False
End If
' array initialized fields
If newBody.IsKind(SyntaxKind.ArgumentList) Then
' the parent ModifiedIdentifier is the active statement
If oldStatement Is oldBody.Parent Then
newStatement = newBody.Parent
Return True
End If
newStatement = Nothing
Return False
End If
' field and property initializers
If TypeOf newBody Is ExpressionSyntax Then
If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
' field
Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax)
Dim oldName As SyntaxToken
If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then
oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier
Else
oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier
End If
For Each newName In newDeclarator.Names
If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then
newStatement = newName
Return True
End If
Next
newStatement = Nothing
Return False
ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' property
If oldStatement Is oldBody.Parent.Parent Then
newStatement = newBody.Parent.Parent
Return True
End If
newStatement = newBody
Return True
End If
End If
' queries
If oldStatement Is oldBody Then
newStatement = newBody
Return True
End If
newStatement = Nothing
Return False
End Function
#End Region
#Region "Syntax And Semantic Utils"
Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan
Return Nothing
End Function
Protected Overrides ReadOnly Property LineDirectiveKeyword As String
Get
Return "ExternalSource"
End Get
End Property
Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort
Get
Return SyntaxKind.ExternalSourceDirectiveTrivia
End Get
End Property
Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit)
Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes)
End Function
Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode
Get
Return SyntaxFactory.CompilationUnit()
End Get
End Property
Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean
' There are no experimental features at this time.
Return False
End Function
Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean
Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2)
End Function
Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean
Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression)
End Function
Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span)
End Function
Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span)
End Function
Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer))
Dim direction As Integer = +1
Dim nodeOrToken As SyntaxNodeOrToken = statement
Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement)
While True
' If the current statement is the last statement of if-block or try-block statements
' pretend there are no siblings following it.
Dim lastBlockStatement As SyntaxNode = Nothing
If nodeOrToken.Parent IsNot Nothing Then
If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault()
End If
End If
If direction > 0 Then
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
Else
nodeOrToken = nodeOrToken.GetNextSibling()
End If
Else
nodeOrToken = nodeOrToken.GetPreviousSibling()
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
End If
End If
If nodeOrToken.RawKind = 0 Then
Dim parent = statement.Parent
If parent Is Nothing Then
Return
End If
If direction > 0 Then
nodeOrToken = statement
direction = -1
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Yield (statement, -1)
End If
nodeOrToken = parent
statement = parent
propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement)
direction = +1
End If
Dim node = nodeOrToken.AsNode()
If node Is Nothing Then
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Dim nodeModifiers = GetFieldOrPropertyModifiers(node)
If Not nodeModifiers.HasValue OrElse
propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then
Continue While
End If
End If
Yield (node, DefaultStatementPart)
End While
End Function
Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList?
If node.IsKind(SyntaxKind.FieldDeclaration) Then
Return DirectCast(node, FieldDeclarationSyntax).Modifiers
ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then
Return DirectCast(node, PropertyStatementSyntax).Modifiers
Else
Return Nothing
End If
End Function
Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean
Return SyntaxFactory.AreEquivalent(left, right)
End Function
Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean
' usual case
If SyntaxFactory.AreEquivalent(left, right) Then
Return True
End If
Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right)
End Function
Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean
If oldStatement.RawKind <> newStatement.RawKind Then
Return False
End If
' Dim a,b,c As <NewExpression>
' We need to check the actual initializer expression in addition to the identifier.
If HasMultiInitializer(oldStatement) Then
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso
AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause,
DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause)
End If
Select Case oldStatement.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Header statements are nops. Changes in the header statements are changes in top-level surface
' which should not be reported as active statement rude edits.
Return True
Case Else
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement)
End Select
End Function
Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean
Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.InterfaceBlock)
End Function
Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean
' No records in VB
Return False
End Function
Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode
Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock?
End Function
Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then
Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList))
declaration = node.Parent.Parent
Return True
End If
If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then
declaration = node.Parent
Return True
End If
declaration = Nothing
Return False
End Function
Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean
Return SyntaxUtilities.HasBackingField(propertyDeclaration)
End Function
Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax)
Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse
declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing)
Case SyntaxKind.ModifiedIdentifier
Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
declaration.Parent.IsKind(SyntaxKind.Parameter))
If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
Return False
End If
Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax)
Return identifier.ArrayBounds IsNot Nothing OrElse
GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing
Case Else
Return False
End Select
End Function
Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean
Return False
End Function
Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax
If equalsValue IsNot Nothing Then
Return equalsValue.Value
End If
If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then
Return DirectCast(asClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
End Function
''' <summary>
''' VB symbols return references that represent the declaration statement.
''' The node that represenets the whole declaration (the block) is the parent node if it exists.
''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body
''' is represented by its declaration statement.
''' </summary>
Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode
Dim syntax = reference.GetSyntax(cancellationToken)
Dim parent = syntax.Parent
Select Case syntax.Kind
' declarations that always have block
Case SyntaxKind.NamespaceStatement
Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock)
Return parent
Case SyntaxKind.ClassStatement
Debug.Assert(parent.Kind = SyntaxKind.ClassBlock)
Return parent
Case SyntaxKind.StructureStatement
Debug.Assert(parent.Kind = SyntaxKind.StructureBlock)
Return parent
Case SyntaxKind.InterfaceStatement
Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock)
Return parent
Case SyntaxKind.ModuleStatement
Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock)
Return parent
Case SyntaxKind.EnumStatement
Debug.Assert(parent.Kind = SyntaxKind.EnumBlock)
Return parent
Case SyntaxKind.SubNewStatement
Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock)
Return parent
Case SyntaxKind.OperatorStatement
Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock)
Return parent
Case SyntaxKind.GetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock)
Return parent
Case SyntaxKind.SetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock)
Return parent
Case SyntaxKind.AddHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock)
Return parent
Case SyntaxKind.RemoveHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock)
Return parent
Case SyntaxKind.RaiseEventAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock)
Return parent
' declarations that may or may not have block
Case SyntaxKind.SubStatement
Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax)
Case SyntaxKind.FunctionStatement
Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax)
Case SyntaxKind.PropertyStatement
Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax)
Case SyntaxKind.EventStatement
Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax)
' declarations that never have a block
Case SyntaxKind.ModifiedIdentifier
Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax)
Return If(variableDeclaration.Names.Count = 1, parent, syntax)
Case SyntaxKind.VariableDeclarator
' fields are represented by ModifiedIdentifier:
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
Case Else
Return syntax
End Select
End Function
Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean
Dim ctor = TryCast(declaration, ConstructorBlockSyntax)
If ctor Is Nothing Then
Return False
End If
' Constructor includes field initializers if the first statement
' isn't a call to another constructor of the declaring class or module.
If ctor.Statements.Count = 0 Then
Return True
End If
Dim firstStatement = ctor.Statements.First
If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then
Return True
End If
Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax)
If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then
Return True
End If
Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return True
End If
Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse
Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then
Return True
End If
' Note that ValueText returns "New" for both New and [New]
If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword)
End Function
Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean
Dim syntaxRefs = type.DeclaringSyntaxReferences
Return syntaxRefs.Length > 1 OrElse
DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword)
End Function
Protected Overrides Function GetSymbolEdits(
editKind As EditKind,
oldNode As SyntaxNode,
newNode As SyntaxNode,
oldModel As SemanticModel,
newModel As SemanticModel,
editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind),
cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind))
Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing
Dim newSymbols As OneOrMany(Of ISymbol) = Nothing
If editKind = EditKind.Delete Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind))
End If
If editKind = EditKind.Insert Then
If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind))
End If
If editKind = EditKind.Update Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse
Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then
Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind))
End If
' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list,
' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits,
' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields.
Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance()
For Each oldSymbol In oldSymbols
Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol)
If newSymbol IsNot Nothing Then
builder.Add((oldSymbol, newSymbol, editKind))
End If
Next
Return OneOrMany.Create(builder.ToImmutableAndFree())
End If
Throw ExceptionUtilities.UnexpectedValue(editKind)
End Function
Private Shared Function TryGetSyntaxNodesForEdit(
editKind As EditKind,
node As SyntaxNode,
model As SemanticModel,
<Out> ByRef symbols As OneOrMany(Of ISymbol),
cancellationToken As CancellationToken) As Boolean
Select Case node.Kind()
Case SyntaxKind.ImportsStatement,
SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock
Return False
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = CType(node, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken)))
Return True
End If
node = variableDeclarator.Names(0)
Case SyntaxKind.FieldDeclaration
If editKind = EditKind.Update Then
Dim field = CType(node, FieldDeclarationSyntax)
If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then
node = field.Declarators(0).Names(0)
Else
symbols = OneOrMany.Create(
(From declarator In field.Declarators
From name In declarator.Names
Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray())
Return True
End If
End If
End Select
Dim symbol = model.GetDeclaredSymbol(node, cancellationToken)
If symbol Is Nothing Then
Return False
End If
' Ignore partial method definition parts.
' Partial method that does not have implementation part is not emitted to metadata.
' Partial method without a definition part is a compilation error.
If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then
Return False
End If
symbols = OneOrMany.Create(symbol)
Return True
End Function
Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean
Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda)
End Function
Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsLambda(node)
End Function
Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax
End Function
Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean
Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2)
End Function
Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetLambda(lambdaBody)
End Function
Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody)
End Function
Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol
Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax)
' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header)
Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol)
End Function
Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode
Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax)
End Function
Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.AggregateClause
Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol)
Case SyntaxKind.CollectionRangeVariable
Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol)
Case SyntaxKind.FunctionAggregation
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.ExpressionRangeVariable
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.FromClause,
SyntaxKind.WhereClause,
SyntaxKind.SkipClause,
SyntaxKind.TakeClause,
SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause,
SyntaxKind.SelectClause
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case Else
Return True
End Select
End Function
Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode))
' VB has no local functions so we don't have anything to report
End Sub
#End Region
#Region "Diagnostic Info"
Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat
Get
Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat
End Get
End Property
Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span)
End Function
Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind)
End Function
Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return GetDiagnosticSpan(node, editKind)
End Function
' internal for testing; kind is passed explicitly for testing as well
Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan?
Select Case kind
Case SyntaxKind.CompilationUnit
Return New TextSpan()
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement
Return node.Span
Case SyntaxKind.NamespaceBlock
Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement)
Case SyntaxKind.NamespaceStatement
Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax))
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock
Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement)
Case SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement
Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax))
Case SyntaxKind.EnumBlock
Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind)
Case SyntaxKind.EnumStatement
Dim enumStatement = DirectCast(node, EnumStatementSyntax)
Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement)
Case SyntaxKind.EventBlock
Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.EventStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.PropertyBlock
Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement)
Case SyntaxKind.PropertyStatement
Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax))
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last)
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return node.Span
Case SyntaxKind.TypeParameter
Return DirectCast(node, TypeParameterSyntax).Identifier.Span
Case SyntaxKind.TypeParameterList,
SyntaxKind.ParameterList,
SyntaxKind.AttributeList,
SyntaxKind.SimpleAsClause
If editKind = EditKind.Delete Then
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Else
Return node.Span
End If
Case SyntaxKind.AttributesStatement,
SyntaxKind.Attribute
Return node.Span
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader)
Case SyntaxKind.MultiLineIfBlock
Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.ElseIfBlock
Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement
Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword)
Case SyntaxKind.SingleLineIfStatement
Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax)
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement.Span
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span
Case SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock,
SyntaxKind.DoLoopUntilBlock
Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span
Case SyntaxKind.ForEachBlock,
SyntaxKind.ForBlock
Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span
Case SyntaxKind.AwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span
Case SyntaxKind.AnonymousObjectCreationExpression
Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax)
Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start,
newWith.Initializer.WithKeyword.Span.End)
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span
Case SyntaxKind.QueryExpression
Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind)
Case SyntaxKind.WhereClause
Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span
Case SyntaxKind.SelectClause
Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span
Case SyntaxKind.FromClause
Return DirectCast(node, FromClauseSyntax).FromKeyword.Span
Case SyntaxKind.AggregateClause
Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span
Case SyntaxKind.LetClause
Return DirectCast(node, LetClauseSyntax).LetKeyword.Span
Case SyntaxKind.SimpleJoinClause
Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span
Case SyntaxKind.GroupJoinClause
Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax)
Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End)
Case SyntaxKind.GroupByClause
Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span
Case SyntaxKind.FunctionAggregation
Return node.Span
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause,
SyntaxKind.SkipWhileClause
Dim partition = DirectCast(node, PartitionWhileClauseSyntax)
Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return node.Span
Case SyntaxKind.JoinCondition
Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span
Case Else
Return node.Span
End Select
End Function
Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan
Return TextSpan.FromBounds(ifKeyword.Span.Start,
If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End))
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan
Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan
Return GetDiagnosticSpan(node.Modifiers,
node.DeclarationKeyword,
If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken)))
End Function
Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan
Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart),
endNode.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan
Dim startToken As SyntaxToken
Dim endToken As SyntaxToken
If header.Modifiers.Count > 0 Then
startToken = header.Modifiers.First
Else
Select Case header.Kind
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword
Case Else
startToken = header.DeclarationKeyword
End Select
End If
If header.ParameterList IsNot Nothing Then
endToken = header.ParameterList.CloseParenToken
Else
Select Case header.Kind
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
endToken = DirectCast(header, MethodStatementSyntax).Identifier
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token
Case SyntaxKind.OperatorStatement
endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken
Case SyntaxKind.SubNewStatement
endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword
Case SyntaxKind.PropertyStatement
endToken = DirectCast(header, PropertyStatementSyntax).Identifier
Case SyntaxKind.EventStatement
endToken = DirectCast(header, EventStatementSyntax).Identifier
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
endToken = DirectCast(header, DelegateStatementSyntax).Identifier
Case SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
endToken = header.DeclarationKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(header.Kind)
End Select
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan
Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword)
Dim endToken As SyntaxToken
If lambda.ParameterList IsNot Nothing Then
endToken = lambda.ParameterList.CloseParenToken
Else
endToken = lambda.DeclarationKeyword
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan
Select Case lambda.Kind
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span
Case Else
Return lambda.Span
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String
Select Case symbol.TypeKind
Case TypeKind.Structure
Return VBFeaturesResources.structure_
Case TypeKind.Module
Return VBFeaturesResources.module_
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String
Select Case symbol.MethodKind
Case MethodKind.StaticConstructor
Return VBFeaturesResources.Shared_constructor
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String
If symbol.IsWithEvents Then
Return VBFeaturesResources.WithEvents_field
End If
Return MyBase.GetDisplayName(symbol)
End Function
Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Return TryGetDisplayNameImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Dim result = TryGetDisplayNameImpl(node, editKind)
If result Is Nothing Then
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End If
Return result
End Function
Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String
Return GetDisplayName(node, editKind)
End Function
Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String
Select Case node.Kind
' top-level
Case SyntaxKind.OptionStatement
Return VBFeaturesResources.option_
Case SyntaxKind.ImportsStatement
Return VBFeaturesResources.import
Case SyntaxKind.NamespaceBlock,
SyntaxKind.NamespaceStatement
Return FeaturesResources.namespace_
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement
Return FeaturesResources.class_
Case SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement
Return VBFeaturesResources.structure_
Case SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement
Return FeaturesResources.interface_
Case SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement
Return VBFeaturesResources.module_
Case SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement
Return FeaturesResources.enum_
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return FeaturesResources.delegate_
Case SyntaxKind.FieldDeclaration
Dim declaration = DirectCast(node, FieldDeclarationSyntax)
Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field,
If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field))
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return FeaturesResources.method
Case SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement
Return FeaturesResources.operator_
Case SyntaxKind.ConstructorBlock
Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.SubNewStatement
Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.PropertyBlock
Return FeaturesResources.property_
Case SyntaxKind.PropertyStatement
Return If(node.IsParentKind(SyntaxKind.PropertyBlock),
FeaturesResources.property_,
FeaturesResources.auto_property)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return FeaturesResources.event_
Case SyntaxKind.EnumMemberDeclaration
Return FeaturesResources.enum_value
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
Return FeaturesResources.property_accessor
Case SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return FeaturesResources.event_accessor
Case SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return FeaturesResources.type_constraint
Case SyntaxKind.SimpleAsClause
Return VBFeaturesResources.as_clause
Case SyntaxKind.TypeParameterList
Return VBFeaturesResources.type_parameters
Case SyntaxKind.TypeParameter
Return FeaturesResources.type_parameter
Case SyntaxKind.ParameterList
Return VBFeaturesResources.parameters
Case SyntaxKind.Parameter
Return FeaturesResources.parameter
Case SyntaxKind.AttributeList,
SyntaxKind.AttributesStatement
Return VBFeaturesResources.attributes
Case SyntaxKind.Attribute
Return FeaturesResources.attribute
' statement-level
Case SyntaxKind.TryBlock
Return VBFeaturesResources.Try_block
Case SyntaxKind.CatchBlock
Return VBFeaturesResources.Catch_clause
Case SyntaxKind.FinallyBlock
Return VBFeaturesResources.Finally_clause
Case SyntaxKind.UsingBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block)
Case SyntaxKind.WithBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block)
Case SyntaxKind.SyncLockBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block)
Case SyntaxKind.ForEachBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block)
Case SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.OnErrorGoToLabelStatement
Return VBFeaturesResources.On_Error_statement
Case SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return VBFeaturesResources.Resume_statement
Case SyntaxKind.YieldStatement
Return VBFeaturesResources.Yield_statement
Case SyntaxKind.AwaitExpression
Return VBFeaturesResources.Await_expression
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return VBFeaturesResources.Lambda
Case SyntaxKind.WhereClause
Return VBFeaturesResources.Where_clause
Case SyntaxKind.SelectClause
Return VBFeaturesResources.Select_clause
Case SyntaxKind.FromClause
Return VBFeaturesResources.From_clause
Case SyntaxKind.AggregateClause
Return VBFeaturesResources.Aggregate_clause
Case SyntaxKind.LetClause
Return VBFeaturesResources.Let_clause
Case SyntaxKind.SimpleJoinClause
Return VBFeaturesResources.Join_clause
Case SyntaxKind.GroupJoinClause
Return VBFeaturesResources.Group_Join_clause
Case SyntaxKind.GroupByClause
Return VBFeaturesResources.Group_By_clause
Case SyntaxKind.FunctionAggregation
Return VBFeaturesResources.Function_aggregation
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause
Return VBFeaturesResources.Take_While_clause
Case SyntaxKind.SkipWhileClause
Return VBFeaturesResources.Skip_While_clause
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return VBFeaturesResources.Ordering_clause
Case SyntaxKind.JoinCondition
Return VBFeaturesResources.Join_condition
Case Else
Return Nothing
End Select
End Function
#End Region
#Region "Top-level Syntactic Rude Edits"
Private Structure EditClassifier
Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer
Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic)
Private ReadOnly _match As Match(Of SyntaxNode)
Private ReadOnly _oldNode As SyntaxNode
Private ReadOnly _newNode As SyntaxNode
Private ReadOnly _kind As EditKind
Private ReadOnly _span As TextSpan?
Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer,
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
oldNode As SyntaxNode,
newNode As SyntaxNode,
kind As EditKind,
Optional match As Match(Of SyntaxNode) = Nothing,
Optional span As TextSpan? = Nothing)
_analyzer = analyzer
_diagnostics = diagnostics
_oldNode = oldNode
_newNode = newNode
_kind = kind
_span = span
_match = match
End Sub
Private Sub ReportError(kind As RudeEditKind)
ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)})
End Sub
Private Sub ReportError(kind As RudeEditKind, args As String())
_diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args))
End Sub
Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode)
_diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)}))
End Sub
Private Function GetSpan() As TextSpan
If _span.HasValue Then
Return _span.Value
End If
If _newNode Is Nothing Then
Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode)
Else
Return GetDiagnosticSpan(_newNode, _kind)
End If
End Function
Public Sub ClassifyEdit()
Select Case _kind
Case EditKind.Delete
ClassifyDelete(_oldNode)
Return
Case EditKind.Update
ClassifyUpdate(_oldNode, _newNode)
Return
Case EditKind.Move
ClassifyMove(_newNode)
Return
Case EditKind.Insert
ClassifyInsert(_newNode)
Return
Case EditKind.Reorder
ClassifyReorder(_oldNode, _newNode)
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(_kind)
End Select
End Sub
#Region "Move and Reorder"
Private Sub ClassifyMove(newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
ReportError(RudeEditKind.Move)
End Select
End Sub
Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint,
SyntaxKind.AttributeList,
SyntaxKind.Attribute
' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
Return
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
' Interface methods. We could allow reordering of non-COM interface methods.
Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock))
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.PropertyStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.EventStatement
' Maybe we could allow changing order of field declarations unless the containing type layout is sequential,
' and it's not a COM interface.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.EnumMemberDeclaration
' To allow this change we would need to check that values of all fields of the enum
' are preserved, or make sure we can update all method bodies that accessed those that changed.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.TypeParameter,
SyntaxKind.Parameter
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(newNode.Kind)
End Select
End Sub
#End Region
#Region "Insert"
Private Sub ClassifyInsert(node As SyntaxNode)
Select Case node.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.AttributesStatement
' Module/assembly attribute
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude
If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude
If node.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Delete"
Private Sub ClassifyDelete(oldNode As SyntaxNode)
Select Case oldNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Delete)
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude edits
If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Update"
Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.NamespaceStatement
ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax))
Return
Case SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Update)
End If
Return
End Select
End Sub
Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax)
Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
ReportError(RudeEditKind.Renamed)
End Sub
Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode)
For Each node In newDeclarationOrBody.DescendantNodesAndSelf()
Select Case node.Kind
Case SyntaxKind.AggregateClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode)
Return
Case SyntaxKind.LocalDeclarationStatement
Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax)
If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then
ReportError(RudeEditKind.UpdateStaticLocal)
End If
End Select
Next
End Sub
#End Region
End Structure
Friend Overrides Sub ReportTopLevelSyntacticRudeEdits(
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
edit As Edit(Of SyntaxNode),
editMap As Dictionary(Of SyntaxNode, EditKind))
' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively.
' For ModifiedIdentifiers though we check the grandparent instead because variables can move across
' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in
' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator.
If edit.Kind = EditKind.Delete AndAlso
edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then
Return
End If
ElseIf edit.Kind = EditKind.Insert AndAlso
edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then
Return
End If
ElseIf HasParentEdit(editMap, edit) Then
Return
End If
Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match)
classifier.ClassifyEdit()
End Sub
Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?)
Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span)
classifier.ClassifyDeclarationBodyRudeUpdates(newMember)
End Sub
#End Region
#Region "Semantic Rude Edits"
Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean
Return oldMethod.HandledEvents.SequenceEqual(
newMethod.HandledEvents,
Function(x, y)
Return x.HandlesKind = y.HandlesKind AndAlso
SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso
SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso
SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty)
End Function)
End Function
Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean)
Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType)
If kind <> RudeEditKind.None Then
diagnostics.Add(New RudeEditDiagnostic(
kind,
GetDiagnosticSpan(newNode, EditKind.Insert),
newNode,
arguments:={GetDisplayName(newNode, EditKind.Insert)}))
End If
End Sub
Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting P/Invoke into a new or existing type is not allowed.
If method.GetDllImportData() IsNot Nothing Then
Return RudeEditKind.InsertDllImport
End If
' Inserting method with handles clause into a new or existing type is not allowed.
If Not method.HandledEvents.IsEmpty Then
Return RudeEditKind.InsertHandlesClause
End If
Case SymbolKind.NamedType
Dim type = CType(newSymbol, INamedTypeSymbol)
' Inserting module is not allowed.
If type.TypeKind = TypeKind.Module Then
Return RudeEditKind.Insert
End If
End Select
' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted):
If Not insertingIntoExistingContainingType Then
Return RudeEditKind.None
End If
If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertIntoGenericType
End If
' Inserting virtual or interface member is not allowed.
If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertVirtual
End If
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting generic method into an existing type is not allowed.
If method.Arity > 0 Then
Return RudeEditKind.InsertGenericMethod
End If
' Inserting operator to an existing type is not allowed.
If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then
Return RudeEditKind.InsertOperator
End If
Return RudeEditKind.None
Case SymbolKind.Field
' Inserting a field into an enum is not allowed.
If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then
Return RudeEditKind.Insert
End If
Return RudeEditKind.None
End Select
Return RudeEditKind.None
End Function
#End Region
#Region "Exception Handling Rude Edits"
Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)()
While node IsNot Nothing
Dim kind = node.Kind
Select Case kind
Case SyntaxKind.TryBlock
If isNonLeaf Then
result.Add(node)
End If
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
result.Add(node)
Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock)
node = node.Parent
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock
' stop at type declaration
Exit While
End Select
' stop at lambda
If LambdaUtilities.IsLambda(node) Then
Exit While
End If
node = node.Parent
End While
Return result
End Function
Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)),
oldStatement As SyntaxNode,
newStatementSpan As TextSpan)
For Each edit In exceptionHandlingEdits
Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind)
If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan)
End If
Next
End Sub
Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.TryBlock
Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax)
Dim newTryBlock = DirectCast(newNode, TryBlockSyntax)
Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso
SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks)
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
Return SyntaxFactory.AreEquivalent(oldNode, newNode)
Case Else
Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind)
End Select
End Function
''' <summary>
''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly.
''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only.
''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only.
''' </summary>
Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan
Select Case node.Kind
Case SyntaxKind.TryBlock
Dim tryBlock = DirectCast(node, TryBlockSyntax)
coversAllChildren = False
If tryBlock.CatchBlocks.Count = 0 Then
Debug.Assert(tryBlock.FinallyBlock IsNot Nothing)
Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End)
End If
Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End)
Case SyntaxKind.CatchBlock
coversAllChildren = True
Return node.Span
Case SyntaxKind.FinallyBlock
coversAllChildren = True
Return DirectCast(node.Parent, TryBlockSyntax).Span
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
#End Region
#Region "State Machines"
Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean
Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse
SyntaxUtilities.IsIteratorMethodOrLambda(declaration)
End Function
Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds)
' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#)
If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body)
kind = StateMachineKinds.Async
ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetYieldStatements(body)
kind = StateMachineKinds.Iterator
Else
suspensionPoints = ImmutableArray(Of SyntaxNode).Empty
kind = StateMachineKinds.None
End If
End Sub
Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode)
' TODO: changes around suspension points (foreach, lock, using, etc.)
If newNode.IsKind(SyntaxKind.AwaitExpression) Then
Dim oldContainingStatementPart = FindContainingStatementPart(oldNode)
Dim newContainingStatementPart = FindContainingStatementPart(newNode)
' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state.
If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso
Not HasNoSpilledState(newNode, newContainingStatementPart) Then
diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span))
End If
End If
End Sub
Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode
Dim statement = TryCast(node, StatementSyntax)
While statement Is Nothing
Select Case node.Parent.Kind()
Case SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.IfStatement,
SyntaxKind.WhileStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SelectStatement,
SyntaxKind.UsingStatement
Return node
End Select
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then
Return node
End If
node = node.Parent
statement = TryCast(node, StatementSyntax)
End While
Return statement
End Function
Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean
Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression))
' There is nothing within the statement part surrounding the await expression.
If containingStatementPart Is awaitExpression Then
Return True
End If
Select Case containingStatementPart.Kind()
Case SyntaxKind.ExpressionStatement,
SyntaxKind.ReturnStatement
Dim expression = GetExpressionFromStatementPart(containingStatementPart)
' Await <expr>
' Return Await <expr>
If expression Is awaitExpression Then
Return True
End If
' <ident> = Await <expr>
' Return <ident> = Await <expr>
Return IsSimpleAwaitAssignment(expression, awaitExpression)
Case SyntaxKind.VariableDeclarator
' <ident> = Await <expr> in using, for, etc
' EqualsValue -> VariableDeclarator
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement
' Until Await <expr>
' UntilClause -> LoopUntilStatement
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LocalDeclarationStatement
' Dim <ident> = Await <expr>
' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement
Return awaitExpression.Parent.Parent.Parent Is containingStatementPart
End Select
Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression)
End Function
Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax
Select Case statement.Kind()
Case SyntaxKind.ExpressionStatement
Return DirectCast(statement, ExpressionStatementSyntax).Expression
Case SyntaxKind.ReturnStatement
Return DirectCast(statement, ReturnStatementSyntax).Expression
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind())
End Select
End Function
Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignment = DirectCast(node, AssignmentStatementSyntax)
Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression
End If
Return False
End Function
#End Region
#Region "Rude Edits around Active Statement"
Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode,
isNonLeaf As Boolean)
Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot)
If onErrorOrResumeStatement IsNot Nothing Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span)
End If
ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement)
End Sub
Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode
For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody)
Select Case node.Kind
Case SyntaxKind.OnErrorGoToLabelStatement,
SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return node
End Select
Next
Return Nothing
End Function
Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode)
' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement.
' Although such changes are technically possible, they might lead to confusion since
' the temporary variables these statements generate won't be properly initialized.
'
' We use a simple algorithm to match each New node with its old counterpart.
' If all nodes match this algorithm Is linear, otherwise it's quadratic.
'
' Unlike exception regions matching where we use LCS, we allow reordering of the statements.
ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement),
areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable,
DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable))
End Sub
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalOverloadsCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public class ExternalOverloadsCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
ExternalCodeFunction parent,
ProjectId projectId)
{
var collection = new ExternalOverloadsCollection(state, parent, projectId);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private readonly ProjectId _projectId;
private ExternalOverloadsCollection(
CodeModelState state,
ExternalCodeFunction parent,
ProjectId projectId)
: base(state, parent)
{
_projectId = projectId;
}
private ExternalCodeFunction ParentElement
{
get { return (ExternalCodeFunction)Parent; }
}
private ImmutableArray<EnvDTE.CodeElement> EnumerateOverloads()
{
var symbol = (IMethodSymbol)ParentElement.LookupSymbol();
// Only methods and constructors can be overloaded. However, all functions
// can successfully return a collection of overloaded functions; if not
// really overloaded, the collection contains just the original function.
if (symbol.MethodKind != MethodKind.Ordinary &&
symbol.MethodKind != MethodKind.Constructor)
{
return ImmutableArray.Create((EnvDTE.CodeElement)Parent);
}
var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance();
foreach (var method in symbol.ContainingType.GetMembers(symbol.Name))
{
if (method.Kind != SymbolKind.Method)
{
continue;
}
var element = ExternalCodeFunction.Create(this.State, _projectId, (IMethodSymbol)method);
if (element != null)
{
overloadsBuilder.Add((EnvDTE.CodeElement)element);
}
}
return overloadsBuilder.ToImmutableAndFree();
}
public override int Count
{
get
{
return EnumerateOverloads().Length;
}
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
if (index >= 0 && index < EnumerateOverloads().Length)
{
element = EnumerateOverloads()[index];
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
element = null;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public class ExternalOverloadsCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
ExternalCodeFunction parent,
ProjectId projectId)
{
var collection = new ExternalOverloadsCollection(state, parent, projectId);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private readonly ProjectId _projectId;
private ExternalOverloadsCollection(
CodeModelState state,
ExternalCodeFunction parent,
ProjectId projectId)
: base(state, parent)
{
_projectId = projectId;
}
private ExternalCodeFunction ParentElement
{
get { return (ExternalCodeFunction)Parent; }
}
private ImmutableArray<EnvDTE.CodeElement> EnumerateOverloads()
{
var symbol = (IMethodSymbol)ParentElement.LookupSymbol();
// Only methods and constructors can be overloaded. However, all functions
// can successfully return a collection of overloaded functions; if not
// really overloaded, the collection contains just the original function.
if (symbol.MethodKind != MethodKind.Ordinary &&
symbol.MethodKind != MethodKind.Constructor)
{
return ImmutableArray.Create((EnvDTE.CodeElement)Parent);
}
var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance();
foreach (var method in symbol.ContainingType.GetMembers(symbol.Name))
{
if (method.Kind != SymbolKind.Method)
{
continue;
}
var element = ExternalCodeFunction.Create(this.State, _projectId, (IMethodSymbol)method);
if (element != null)
{
overloadsBuilder.Add((EnvDTE.CodeElement)element);
}
}
return overloadsBuilder.ToImmutableAndFree();
}
public override int Count
{
get
{
return EnumerateOverloads().Length;
}
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
if (index >= 0 && index < EnumerateOverloads().Length)
{
element = EnumerateOverloads()[index];
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
element = null;
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/VisualBasic/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.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.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class NamespaceDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of NamespaceStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
namespaceDeclaration As NamespaceStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(namespaceDeclaration, spans, optionProvider)
Dim block = TryCast(namespaceDeclaration.Parent, NamespaceBlockSyntax)
If Not block?.EndNamespaceStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=namespaceDeclaration, autoCollapse:=False,
type:=BlockTypes.Namespace, isCollapsible:=True))
CollectCommentsRegions(block.EndNamespaceStatement, spans, optionProvider)
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.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class NamespaceDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of NamespaceStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
namespaceDeclaration As NamespaceStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(namespaceDeclaration, spans, optionProvider)
Dim block = TryCast(namespaceDeclaration.Parent, NamespaceBlockSyntax)
If Not block?.EndNamespaceStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=namespaceDeclaration, autoCollapse:=False,
type:=BlockTypes.Namespace, isCollapsible:=True))
CollectCommentsRegions(block.EndNamespaceStatement, spans, optionProvider)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/BraceCompletion/IBraceCompletionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.BraceCompletion
{
internal interface IBraceCompletionService : ILanguageService
{
/// <summary>
/// Checks if this brace completion service should be the service used to provide brace completions at
/// the specified position with the specified opening brace.
///
/// Only one implementation of <see cref="IBraceCompletionService"/> should return true
/// for a given brace, opening position, and document. Only that service will be asked
/// for brace completion results.
/// </summary>
/// <param name="brace">
/// The opening brace character to be inserted at the opening position.</param>
/// <param name="openingPosition">
/// The opening position to insert the brace.
/// Note that the brace is not yet inserted at this position in the document.
/// </param>
/// <param name="document">The document to insert the brace at the position.</param>
/// <param name="cancellationToken">A cancellation token.</param>
Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken);
/// <summary>
/// Returns the text change to add the closing brace given the context.
/// </summary>
Task<BraceCompletionResult?> GetBraceCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
/// <summary>
/// Returns any text changes that need to be made after adding the closing brace.
/// </summary>
/// <remarks>
/// This cannot be merged with <see cref="GetBraceCompletionAsync(BraceCompletionContext, CancellationToken)"/>
/// as we need to swap the editor tracking mode of the closing point from positive to negative
/// in BraceCompletionSessionProvider.BraceCompletionSession.Start after completing the brace and before
/// doing any kind of formatting on it. So these must be two distinct steps until we fully move to LSP.
/// </remarks>
Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
/// <summary>
/// Get any text changes that should be applied after the enter key is typed inside a brace completion context.
/// </summary>
Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(BraceCompletionContext braceCompletionContext, DocumentOptionSet documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the brace completion context if the caret is located between an already completed
/// set of braces with only whitespace in between.
/// </summary>
Task<BraceCompletionContext?> GetCompletedBraceContextAsync(Document document, int caretLocation, CancellationToken cancellationToken);
/// <summary>
/// Returns true if over typing should be allowed given the caret location and completed pair of braces.
/// For example some providers allow over typing in non-user code and others do not.
/// </summary>
Task<bool> AllowOverTypeAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
}
internal readonly struct BraceCompletionResult
{
/// <summary>
/// The set of text changes that should be applied to the input text to retrieve the
/// brace completion result.
/// </summary>
public ImmutableArray<TextChange> TextChanges { get; }
/// <summary>
/// The caret location in the new text created by applying all <see cref="TextChanges"/>
/// to the input text. Note the column in the line position can be virtual in that it points
/// to a location in the line which does not actually contain whitespace.
/// Hosts can determine how best to handle that virtual location.
/// For example, placing the character in virtual space (when suppported)
/// or inserting an appropriate number of spaces into the document".
/// </summary>
public LinePosition CaretLocation { get; }
public BraceCompletionResult(ImmutableArray<TextChange> textChanges, LinePosition caretLocation)
{
CaretLocation = caretLocation;
TextChanges = textChanges;
}
}
internal readonly struct BraceCompletionContext
{
public Document Document { get; }
public int OpeningPoint { get; }
public int ClosingPoint { get; }
public int CaretLocation { get; }
public BraceCompletionContext(Document document, int openingPoint, int closingPoint, int caretLocation)
{
Document = document;
OpeningPoint = openingPoint;
ClosingPoint = closingPoint;
CaretLocation = caretLocation;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.BraceCompletion
{
internal interface IBraceCompletionService : ILanguageService
{
/// <summary>
/// Checks if this brace completion service should be the service used to provide brace completions at
/// the specified position with the specified opening brace.
///
/// Only one implementation of <see cref="IBraceCompletionService"/> should return true
/// for a given brace, opening position, and document. Only that service will be asked
/// for brace completion results.
/// </summary>
/// <param name="brace">
/// The opening brace character to be inserted at the opening position.</param>
/// <param name="openingPosition">
/// The opening position to insert the brace.
/// Note that the brace is not yet inserted at this position in the document.
/// </param>
/// <param name="document">The document to insert the brace at the position.</param>
/// <param name="cancellationToken">A cancellation token.</param>
Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken);
/// <summary>
/// Returns the text change to add the closing brace given the context.
/// </summary>
Task<BraceCompletionResult?> GetBraceCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
/// <summary>
/// Returns any text changes that need to be made after adding the closing brace.
/// </summary>
/// <remarks>
/// This cannot be merged with <see cref="GetBraceCompletionAsync(BraceCompletionContext, CancellationToken)"/>
/// as we need to swap the editor tracking mode of the closing point from positive to negative
/// in BraceCompletionSessionProvider.BraceCompletionSession.Start after completing the brace and before
/// doing any kind of formatting on it. So these must be two distinct steps until we fully move to LSP.
/// </remarks>
Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
/// <summary>
/// Get any text changes that should be applied after the enter key is typed inside a brace completion context.
/// </summary>
Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(BraceCompletionContext braceCompletionContext, DocumentOptionSet documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the brace completion context if the caret is located between an already completed
/// set of braces with only whitespace in between.
/// </summary>
Task<BraceCompletionContext?> GetCompletedBraceContextAsync(Document document, int caretLocation, CancellationToken cancellationToken);
/// <summary>
/// Returns true if over typing should be allowed given the caret location and completed pair of braces.
/// For example some providers allow over typing in non-user code and others do not.
/// </summary>
Task<bool> AllowOverTypeAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken);
}
internal readonly struct BraceCompletionResult
{
/// <summary>
/// The set of text changes that should be applied to the input text to retrieve the
/// brace completion result.
/// </summary>
public ImmutableArray<TextChange> TextChanges { get; }
/// <summary>
/// The caret location in the new text created by applying all <see cref="TextChanges"/>
/// to the input text. Note the column in the line position can be virtual in that it points
/// to a location in the line which does not actually contain whitespace.
/// Hosts can determine how best to handle that virtual location.
/// For example, placing the character in virtual space (when suppported)
/// or inserting an appropriate number of spaces into the document".
/// </summary>
public LinePosition CaretLocation { get; }
public BraceCompletionResult(ImmutableArray<TextChange> textChanges, LinePosition caretLocation)
{
CaretLocation = caretLocation;
TextChanges = textChanges;
}
}
internal readonly struct BraceCompletionContext
{
public Document Document { get; }
public int OpeningPoint { get; }
public int ClosingPoint { get; }
public int CaretLocation { get; }
public BraceCompletionContext(Document document, int openingPoint, int closingPoint, int caretLocation)
{
Document = document;
OpeningPoint = openingPoint;
ClosingPoint = closingPoint;
CaretLocation = caretLocation;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/TestUtilities/Diagnostics/TestAnalyzerReferenceByLanguage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class TestAnalyzerReferenceByLanguage : AnalyzerReference
{
private readonly IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> _analyzersMap;
public TestAnalyzerReferenceByLanguage(IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzersMap, string? fullPath = null)
{
_analyzersMap = analyzersMap;
FullPath = fullPath;
}
public override string? FullPath { get; }
public override string Display => nameof(TestAnalyzerReferenceByLanguage);
public override object Id => Display;
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages()
=> _analyzersMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language)
{
if (_analyzersMap.TryGetValue(language, out var analyzers))
{
return analyzers;
}
return ImmutableArray<DiagnosticAnalyzer>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal class TestAnalyzerReferenceByLanguage : AnalyzerReference
{
private readonly IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> _analyzersMap;
public TestAnalyzerReferenceByLanguage(IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzersMap, string? fullPath = null)
{
_analyzersMap = analyzersMap;
FullPath = fullPath;
}
public override string? FullPath { get; }
public override string Display => nameof(TestAnalyzerReferenceByLanguage);
public override object Id => Display;
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages()
=> _analyzersMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language)
{
if (_analyzersMap.TryGetValue(language, out var analyzers))
{
return analyzers;
}
return ImmutableArray<DiagnosticAnalyzer>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/Emit/EditAndContinue/SymbolChange.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal enum SymbolChange
{
/// <summary>
/// No change to symbol or members.
/// </summary>
None = 0,
/// <summary>
/// No change to symbol but may contain changed symbols.
/// </summary>
ContainsChanges,
/// <summary>
/// Symbol updated.
/// </summary>
Updated,
/// <summary>
/// Symbol added.
/// </summary>
Added,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal enum SymbolChange
{
/// <summary>
/// No change to symbol or members.
/// </summary>
None = 0,
/// <summary>
/// No change to symbol but may contain changed symbols.
/// </summary>
ContainsChanges,
/// <summary>
/// Symbol updated.
/// </summary>
Updated,
/// <summary>
/// Symbol added.
/// </summary>
Added,
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./eng/SourceBuildPrebuiltBaseline.xml | <UsageData>
<IgnorePatterns>
<UsagePattern IdentityGlob="*/*" />
</IgnorePatterns>
</UsageData>
| <UsageData>
<IgnorePatterns>
<UsagePattern IdentityGlob="*/*" />
</IgnorePatterns>
</UsageData>
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/Symbols/IMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a method or method-like symbol (including constructor,
/// destructor, operator, or property/event accessor).
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IMethodSymbol : ISymbol
{
/// <summary>
/// Gets what kind of method this is. There are several different kinds of things in the
/// C# language that are represented as methods. This property allow distinguishing those things
/// without having to decode the name of the method.
/// </summary>
MethodKind MethodKind { get; }
/// <summary>
/// Returns the arity of this method, or the number of type parameters it takes.
/// A non-generic method has zero arity.
/// </summary>
int Arity { get; }
/// <summary>
/// Returns whether this method is generic; i.e., does it have any type parameters?
/// </summary>
bool IsGenericMethod { get; }
/// <summary>
/// Returns true if this method is an extension method.
/// </summary>
bool IsExtensionMethod { get; }
/// <summary>
/// Returns true if this method is an async method
/// </summary>
bool IsAsync { get; }
/// <summary>
/// Returns whether this method is using CLI VARARG calling convention. This is used for
/// C-style variable argument lists. This is used extremely rarely in C# code and is
/// represented using the undocumented "__arglist" keyword.
///
/// Note that methods with "params" on the last parameter are indicated with the "IsParams"
/// property on ParameterSymbol, and are not represented with this property.
/// </summary>
bool IsVararg { get; }
/// <summary>
/// Returns whether this built-in operator checks for integer overflow.
/// </summary>
bool IsCheckedBuiltin { get; }
/// <summary>
/// Returns true if this method hides base methods by name. This cannot be specified directly
/// in the C# language, but can be true for methods defined in other languages imported from
/// metadata. The equivalent of the "hidebyname" flag in metadata.
/// </summary>
bool HidesBaseMethodsByName { get; }
/// <summary>
/// Returns true if this method has no return type; i.e., returns "void".
/// </summary>
bool ReturnsVoid { get; }
/// <summary>
/// Returns true if this method returns by reference.
/// </summary>
bool ReturnsByRef { get; }
/// <summary>
/// Returns true if this method returns by ref readonly.
/// </summary>
bool ReturnsByRefReadonly { get; }
/// <summary>
/// Returns the RefKind of the method.
/// </summary>
RefKind RefKind { get; }
/// <summary>
/// Gets the return type of the method.
/// </summary>
ITypeSymbol ReturnType { get; }
/// <summary>
/// Gets the top-level nullability of the return type of the method.
/// </summary>
NullableAnnotation ReturnNullableAnnotation { get; }
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a given type parameter,
/// then the type parameter itself is consider the type argument.
/// </summary>
ImmutableArray<ITypeSymbol> TypeArguments { get; }
/// <summary>
/// Returns the top-level nullability of the type arguments that have been substituted
/// for the type parameters. If nothing has been substituted for a given type parameter,
/// then <see cref="NullableAnnotation.None"/> is returned.
/// </summary>
ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; }
/// <summary>
/// Get the type parameters on this method. If the method has not generic,
/// returns an empty list.
/// </summary>
ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
/// <summary>
/// Gets the parameters of this method. If this method has no parameters, returns
/// an empty list.
/// </summary>
ImmutableArray<IParameterSymbol> Parameters { get; }
/// <summary>
/// Returns the method symbol that this method was constructed from. The resulting
/// method symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
IMethodSymbol ConstructedFrom { get; }
/// <summary>
/// Indicates whether the method is readonly,
/// i.e. whether the 'this' receiver parameter is 'ref readonly'.
/// Returns true for readonly instance methods and accessors
/// and for reduced extension methods with a 'this in' parameter.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true for 'init' set accessors, and false otherwise.
/// </summary>
bool IsInitOnly { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IMethodSymbol OriginalDefinition { get; }
/// <summary>
/// If this method overrides another method (because it both had the override modifier
/// and there correctly was a method to override), returns the overridden method.
/// </summary>
IMethodSymbol? OverriddenMethod { get; }
/// <summary>
/// If this method can be applied to an object, returns the type of object it is applied to.
/// </summary>
ITypeSymbol? ReceiverType { get; }
/// <summary>
/// If this method can be applied to an object, returns the top-level nullability of the object it is applied to.
/// </summary>
NullableAnnotation ReceiverNullableAnnotation { get; }
/// <summary>
/// If this method is a reduced extension method, returns the definition of extension
/// method from which this was reduced. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReducedFrom { get; }
/// <summary>
/// If this method is a reduced extension method, returns a type inferred during reduction process for the type parameter.
/// </summary>
/// <param name="reducedFromTypeParameter">Type parameter of the corresponding <see cref="ReducedFrom"/> method.</param>
/// <returns>Inferred type or Nothing if nothing was inferred.</returns>
/// <exception cref="System.InvalidOperationException">If this is not a reduced extension method.</exception>
/// <exception cref="System.ArgumentNullException">If <paramref name="reducedFromTypeParameter"/> is null.</exception>
/// <exception cref="System.ArgumentException">If <paramref name="reducedFromTypeParameter"/> doesn't belong to the corresponding <see cref="ReducedFrom"/> method.</exception>
ITypeSymbol? GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
/// <summary>
/// If this is an extension method that can be applied to a receiver of the given type,
/// returns a reduced extension method symbol thus formed. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReduceExtensionMethod(ITypeSymbol receiverType);
/// <summary>
/// Returns interface methods explicitly implemented by this method.
/// </summary>
/// <remarks>
/// Methods imported from metadata can explicitly implement more than one method,
/// that is why return type is ImmutableArray.
/// </remarks>
ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
/// <summary>
/// Returns the list of custom modifiers, if any, associated with the return type.
/// </summary>
ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get; }
/// <summary>
/// Custom modifiers associated with the ref modifier, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> RefCustomModifiers { get; }
/// <summary>
/// Returns the list of custom attributes, if any, associated with the returned value.
/// </summary>
ImmutableArray<AttributeData> GetReturnTypeAttributes();
/// <summary>
/// The calling convention enum of the method symbol.
/// </summary>
SignatureCallingConvention CallingConvention { get; }
/// <summary>
/// Modifier types that are considered part of the calling convention of this method, if the <see cref="MethodKind"/> is <see cref="MethodKind.FunctionPointerSignature"/>
/// and the <see cref="CallingConvention"/> is <see cref="SignatureCallingConvention.Unmanaged"/>. If this is not a function pointer signature or the calling convention is
/// not unmanaged, this is an empty array. Order and duplication of these modifiers reflect source/metadata order and duplication, whichever this symbol came from.
/// </summary>
ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes { get; }
/// <summary>
/// Returns a symbol (e.g. property, event, etc.) associated with the method.
/// </summary>
/// <remarks>
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.PropertyGet"/> or <see cref="MethodKind.PropertySet"/>,
/// returns the property that this method is the getter or setter for.
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.EventAdd"/> or <see cref="MethodKind.EventRemove"/>,
/// returns the event that this method is the adder or remover for.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </remarks>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns a constructed method given its type arguments.
/// </summary>
/// <param name="typeArguments">The immediate type arguments to be replaced for type
/// parameters in the method.</param>
IMethodSymbol Construct(params ITypeSymbol[] typeArguments);
/// <summary>
/// Returns a constructed method given its type arguments and type argument nullable annotations.
/// </summary>
IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations);
/// <summary>
/// If this is a partial method implementation part, returns the corresponding
/// definition part. Otherwise null.
/// </summary>
IMethodSymbol? PartialDefinitionPart { get; }
/// <summary>
/// If this is a partial method declaration without a body, and the method is
/// implemented with a body, returns that implementing definition. Otherwise
/// null.
/// </summary>
IMethodSymbol? PartialImplementationPart { get; }
/// <summary>
/// Returns the implementation flags for the given method symbol.
/// </summary>
MethodImplAttributes MethodImplementationFlags { get; }
/// <summary>
/// Return true if this is a partial method definition without a body. If there
/// is an implementing body, it can be retrieved with <see cref="PartialImplementationPart"/>.
/// </summary>
bool IsPartialDefinition { get; }
/// <summary>
/// Platform invoke information, or null if the method isn't a P/Invoke.
/// </summary>
DllImportData? GetDllImportData();
/// <summary>
/// If this method is a Lambda method (MethodKind = MethodKind.LambdaMethod) and
/// there is an anonymous delegate associated with it, returns this delegate.
///
/// Returns null if the symbol is not a lambda or if it does not have an
/// anonymous delegate associated with it.
/// </summary>
INamedTypeSymbol? AssociatedAnonymousDelegate { get; }
/// <summary>
/// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute.
/// </summary>
bool IsConditional { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a method or method-like symbol (including constructor,
/// destructor, operator, or property/event accessor).
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IMethodSymbol : ISymbol
{
/// <summary>
/// Gets what kind of method this is. There are several different kinds of things in the
/// C# language that are represented as methods. This property allow distinguishing those things
/// without having to decode the name of the method.
/// </summary>
MethodKind MethodKind { get; }
/// <summary>
/// Returns the arity of this method, or the number of type parameters it takes.
/// A non-generic method has zero arity.
/// </summary>
int Arity { get; }
/// <summary>
/// Returns whether this method is generic; i.e., does it have any type parameters?
/// </summary>
bool IsGenericMethod { get; }
/// <summary>
/// Returns true if this method is an extension method.
/// </summary>
bool IsExtensionMethod { get; }
/// <summary>
/// Returns true if this method is an async method
/// </summary>
bool IsAsync { get; }
/// <summary>
/// Returns whether this method is using CLI VARARG calling convention. This is used for
/// C-style variable argument lists. This is used extremely rarely in C# code and is
/// represented using the undocumented "__arglist" keyword.
///
/// Note that methods with "params" on the last parameter are indicated with the "IsParams"
/// property on ParameterSymbol, and are not represented with this property.
/// </summary>
bool IsVararg { get; }
/// <summary>
/// Returns whether this built-in operator checks for integer overflow.
/// </summary>
bool IsCheckedBuiltin { get; }
/// <summary>
/// Returns true if this method hides base methods by name. This cannot be specified directly
/// in the C# language, but can be true for methods defined in other languages imported from
/// metadata. The equivalent of the "hidebyname" flag in metadata.
/// </summary>
bool HidesBaseMethodsByName { get; }
/// <summary>
/// Returns true if this method has no return type; i.e., returns "void".
/// </summary>
bool ReturnsVoid { get; }
/// <summary>
/// Returns true if this method returns by reference.
/// </summary>
bool ReturnsByRef { get; }
/// <summary>
/// Returns true if this method returns by ref readonly.
/// </summary>
bool ReturnsByRefReadonly { get; }
/// <summary>
/// Returns the RefKind of the method.
/// </summary>
RefKind RefKind { get; }
/// <summary>
/// Gets the return type of the method.
/// </summary>
ITypeSymbol ReturnType { get; }
/// <summary>
/// Gets the top-level nullability of the return type of the method.
/// </summary>
NullableAnnotation ReturnNullableAnnotation { get; }
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a given type parameter,
/// then the type parameter itself is consider the type argument.
/// </summary>
ImmutableArray<ITypeSymbol> TypeArguments { get; }
/// <summary>
/// Returns the top-level nullability of the type arguments that have been substituted
/// for the type parameters. If nothing has been substituted for a given type parameter,
/// then <see cref="NullableAnnotation.None"/> is returned.
/// </summary>
ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; }
/// <summary>
/// Get the type parameters on this method. If the method has not generic,
/// returns an empty list.
/// </summary>
ImmutableArray<ITypeParameterSymbol> TypeParameters { get; }
/// <summary>
/// Gets the parameters of this method. If this method has no parameters, returns
/// an empty list.
/// </summary>
ImmutableArray<IParameterSymbol> Parameters { get; }
/// <summary>
/// Returns the method symbol that this method was constructed from. The resulting
/// method symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
IMethodSymbol ConstructedFrom { get; }
/// <summary>
/// Indicates whether the method is readonly,
/// i.e. whether the 'this' receiver parameter is 'ref readonly'.
/// Returns true for readonly instance methods and accessors
/// and for reduced extension methods with a 'this in' parameter.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true for 'init' set accessors, and false otherwise.
/// </summary>
bool IsInitOnly { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IMethodSymbol OriginalDefinition { get; }
/// <summary>
/// If this method overrides another method (because it both had the override modifier
/// and there correctly was a method to override), returns the overridden method.
/// </summary>
IMethodSymbol? OverriddenMethod { get; }
/// <summary>
/// If this method can be applied to an object, returns the type of object it is applied to.
/// </summary>
ITypeSymbol? ReceiverType { get; }
/// <summary>
/// If this method can be applied to an object, returns the top-level nullability of the object it is applied to.
/// </summary>
NullableAnnotation ReceiverNullableAnnotation { get; }
/// <summary>
/// If this method is a reduced extension method, returns the definition of extension
/// method from which this was reduced. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReducedFrom { get; }
/// <summary>
/// If this method is a reduced extension method, returns a type inferred during reduction process for the type parameter.
/// </summary>
/// <param name="reducedFromTypeParameter">Type parameter of the corresponding <see cref="ReducedFrom"/> method.</param>
/// <returns>Inferred type or Nothing if nothing was inferred.</returns>
/// <exception cref="System.InvalidOperationException">If this is not a reduced extension method.</exception>
/// <exception cref="System.ArgumentNullException">If <paramref name="reducedFromTypeParameter"/> is null.</exception>
/// <exception cref="System.ArgumentException">If <paramref name="reducedFromTypeParameter"/> doesn't belong to the corresponding <see cref="ReducedFrom"/> method.</exception>
ITypeSymbol? GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter);
/// <summary>
/// If this is an extension method that can be applied to a receiver of the given type,
/// returns a reduced extension method symbol thus formed. Otherwise, returns null.
/// </summary>
IMethodSymbol? ReduceExtensionMethod(ITypeSymbol receiverType);
/// <summary>
/// Returns interface methods explicitly implemented by this method.
/// </summary>
/// <remarks>
/// Methods imported from metadata can explicitly implement more than one method,
/// that is why return type is ImmutableArray.
/// </remarks>
ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; }
/// <summary>
/// Returns the list of custom modifiers, if any, associated with the return type.
/// </summary>
ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get; }
/// <summary>
/// Custom modifiers associated with the ref modifier, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> RefCustomModifiers { get; }
/// <summary>
/// Returns the list of custom attributes, if any, associated with the returned value.
/// </summary>
ImmutableArray<AttributeData> GetReturnTypeAttributes();
/// <summary>
/// The calling convention enum of the method symbol.
/// </summary>
SignatureCallingConvention CallingConvention { get; }
/// <summary>
/// Modifier types that are considered part of the calling convention of this method, if the <see cref="MethodKind"/> is <see cref="MethodKind.FunctionPointerSignature"/>
/// and the <see cref="CallingConvention"/> is <see cref="SignatureCallingConvention.Unmanaged"/>. If this is not a function pointer signature or the calling convention is
/// not unmanaged, this is an empty array. Order and duplication of these modifiers reflect source/metadata order and duplication, whichever this symbol came from.
/// </summary>
ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes { get; }
/// <summary>
/// Returns a symbol (e.g. property, event, etc.) associated with the method.
/// </summary>
/// <remarks>
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.PropertyGet"/> or <see cref="MethodKind.PropertySet"/>,
/// returns the property that this method is the getter or setter for.
/// If this method has <see cref="MethodKind"/> of <see cref="MethodKind.EventAdd"/> or <see cref="MethodKind.EventRemove"/>,
/// returns the event that this method is the adder or remover for.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </remarks>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns a constructed method given its type arguments.
/// </summary>
/// <param name="typeArguments">The immediate type arguments to be replaced for type
/// parameters in the method.</param>
IMethodSymbol Construct(params ITypeSymbol[] typeArguments);
/// <summary>
/// Returns a constructed method given its type arguments and type argument nullable annotations.
/// </summary>
IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations);
/// <summary>
/// If this is a partial method implementation part, returns the corresponding
/// definition part. Otherwise null.
/// </summary>
IMethodSymbol? PartialDefinitionPart { get; }
/// <summary>
/// If this is a partial method declaration without a body, and the method is
/// implemented with a body, returns that implementing definition. Otherwise
/// null.
/// </summary>
IMethodSymbol? PartialImplementationPart { get; }
/// <summary>
/// Returns the implementation flags for the given method symbol.
/// </summary>
MethodImplAttributes MethodImplementationFlags { get; }
/// <summary>
/// Return true if this is a partial method definition without a body. If there
/// is an implementing body, it can be retrieved with <see cref="PartialImplementationPart"/>.
/// </summary>
bool IsPartialDefinition { get; }
/// <summary>
/// Platform invoke information, or null if the method isn't a P/Invoke.
/// </summary>
DllImportData? GetDllImportData();
/// <summary>
/// If this method is a Lambda method (MethodKind = MethodKind.LambdaMethod) and
/// there is an anonymous delegate associated with it, returns this delegate.
///
/// Returns null if the symbol is not a lambda or if it does not have an
/// anonymous delegate associated with it.
/// </summary>
INamedTypeSymbol? AssociatedAnonymousDelegate { get; }
/// <summary>
/// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute.
/// </summary>
bool IsConditional { get; }
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/EESymbolProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection.Metadata;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal abstract class EESymbolProvider<TTypeSymbol, TLocalSymbol>
where TTypeSymbol : class, ITypeSymbolInternal
where TLocalSymbol : class, ILocalSymbolInternal
{
/// <summary>
/// Windows PDB constant signature format.
/// </summary>
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public abstract TTypeSymbol DecodeLocalVariableType(ImmutableArray<byte> signature);
/// <summary>
/// Portable PDB constant signature format.
/// </summary>
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public abstract void DecodeLocalConstant(ref BlobReader reader, out TTypeSymbol type, out ConstantValue value);
public abstract TTypeSymbol GetTypeSymbolForSerializedType(string typeName);
public abstract TLocalSymbol GetLocalVariable(
string? name,
int slotIndex,
LocalInfo<TTypeSymbol> info,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt);
public abstract TLocalSymbol GetLocalConstant(
string name,
TTypeSymbol type,
ConstantValue value,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt);
/// <exception cref="BadImageFormatException"></exception>
public abstract IAssemblySymbolInternal GetReferencedAssembly(AssemblyReferenceHandle handle);
/// <exception cref="BadImageFormatException"></exception>
public abstract TTypeSymbol GetType(EntityHandle handle);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection.Metadata;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal abstract class EESymbolProvider<TTypeSymbol, TLocalSymbol>
where TTypeSymbol : class, ITypeSymbolInternal
where TLocalSymbol : class, ILocalSymbolInternal
{
/// <summary>
/// Windows PDB constant signature format.
/// </summary>
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public abstract TTypeSymbol DecodeLocalVariableType(ImmutableArray<byte> signature);
/// <summary>
/// Portable PDB constant signature format.
/// </summary>
/// <exception cref="BadImageFormatException"></exception>
/// <exception cref="UnsupportedSignatureContent"></exception>
public abstract void DecodeLocalConstant(ref BlobReader reader, out TTypeSymbol type, out ConstantValue value);
public abstract TTypeSymbol GetTypeSymbolForSerializedType(string typeName);
public abstract TLocalSymbol GetLocalVariable(
string? name,
int slotIndex,
LocalInfo<TTypeSymbol> info,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt);
public abstract TLocalSymbol GetLocalConstant(
string name,
TTypeSymbol type,
ConstantValue value,
ImmutableArray<bool> dynamicFlagsOpt,
ImmutableArray<string?> tupleElementNamesOpt);
/// <exception cref="BadImageFormatException"></exception>
public abstract IAssemblySymbolInternal GetReferencedAssembly(AssemblyReferenceHandle handle);
/// <exception cref="BadImageFormatException"></exception>
public abstract TTypeSymbol GetType(EntityHandle handle);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/InProcComponent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using EnvDTE;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
/// <summary>
/// Base class for all components that run inside of the Visual Studio process.
/// <list type="bullet">
/// <item>Every in-proc component should provide a public, static, parameterless "Create" method.
/// This will be called to construct the component in the VS process.</item>
/// <item>Public methods on in-proc components should be instance methods to ensure that they are
/// marshalled properly and execute in the VS process. Static methods will execute in the process
/// in which they are called.</item>
/// </list>
/// </summary>
internal abstract class InProcComponent : MarshalByRefObject
{
private static JoinableTaskFactory? _joinableTaskFactory;
protected InProcComponent() { }
private static Dispatcher CurrentApplicationDispatcher
=> Application.Current.Dispatcher;
protected static JoinableTaskFactory JoinableTaskFactory
{
get
{
if (_joinableTaskFactory is null)
{
Interlocked.CompareExchange(ref _joinableTaskFactory, ThreadHelper.JoinableTaskFactory.WithPriority(CurrentApplicationDispatcher, DispatcherPriority.Background), null);
}
return _joinableTaskFactory;
}
}
protected static void InvokeOnUIThread(Action<CancellationToken> action)
{
using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);
var operation = JoinableTaskFactory.RunAsync(async () =>
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token);
action(cancellationTokenSource.Token);
});
operation.Task.Wait(cancellationTokenSource.Token);
}
protected static T InvokeOnUIThread<T>(Func<CancellationToken, T> action)
{
using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);
var operation = JoinableTaskFactory.RunAsync(async () =>
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token);
return action(cancellationTokenSource.Token);
});
operation.Task.Wait(cancellationTokenSource.Token);
return operation.Task.Result;
}
protected static TInterface GetGlobalService<TService, TInterface>()
where TService : class
where TInterface : class
=> InvokeOnUIThread(cancellationToken => (TInterface)ServiceProvider.GlobalProvider.GetService(typeof(TService)));
protected static TService GetComponentModelService<TService>()
where TService : class
=> InvokeOnUIThread(cancellationToken => GetComponentModel().GetService<TService>());
protected static DTE GetDTE()
=> GetGlobalService<SDTE, DTE>();
protected static IComponentModel GetComponentModel()
=> GetGlobalService<SComponentModel, IComponentModel>();
protected static bool IsCommandAvailable(string commandName)
=> GetDTE().Commands.Item(commandName).IsAvailable;
protected static void ExecuteCommand(string commandName, string args = "")
{
var task = Task.Run(() => GetDTE().ExecuteCommand(commandName, args));
task.Wait(Helper.HangMitigatingTimeout);
}
/// <summary>
/// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT).
/// </summary>
protected static void WaitForApplicationIdle(TimeSpan timeout)
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
=> CurrentApplicationDispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle).Wait(timeout);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
protected static void WaitForSystemIdle()
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
=> CurrentApplicationDispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
// Ensure InProcComponents live forever
public override object? InitializeLifetimeService() => 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.Threading;
using System.Windows;
using System.Windows.Threading;
using EnvDTE;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
/// <summary>
/// Base class for all components that run inside of the Visual Studio process.
/// <list type="bullet">
/// <item>Every in-proc component should provide a public, static, parameterless "Create" method.
/// This will be called to construct the component in the VS process.</item>
/// <item>Public methods on in-proc components should be instance methods to ensure that they are
/// marshalled properly and execute in the VS process. Static methods will execute in the process
/// in which they are called.</item>
/// </list>
/// </summary>
internal abstract class InProcComponent : MarshalByRefObject
{
private static JoinableTaskFactory? _joinableTaskFactory;
protected InProcComponent() { }
private static Dispatcher CurrentApplicationDispatcher
=> Application.Current.Dispatcher;
protected static JoinableTaskFactory JoinableTaskFactory
{
get
{
if (_joinableTaskFactory is null)
{
Interlocked.CompareExchange(ref _joinableTaskFactory, ThreadHelper.JoinableTaskFactory.WithPriority(CurrentApplicationDispatcher, DispatcherPriority.Background), null);
}
return _joinableTaskFactory;
}
}
protected static void InvokeOnUIThread(Action<CancellationToken> action)
{
using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);
var operation = JoinableTaskFactory.RunAsync(async () =>
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token);
action(cancellationTokenSource.Token);
});
operation.Task.Wait(cancellationTokenSource.Token);
}
protected static T InvokeOnUIThread<T>(Func<CancellationToken, T> action)
{
using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout);
var operation = JoinableTaskFactory.RunAsync(async () =>
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token);
return action(cancellationTokenSource.Token);
});
operation.Task.Wait(cancellationTokenSource.Token);
return operation.Task.Result;
}
protected static TInterface GetGlobalService<TService, TInterface>()
where TService : class
where TInterface : class
=> InvokeOnUIThread(cancellationToken => (TInterface)ServiceProvider.GlobalProvider.GetService(typeof(TService)));
protected static TService GetComponentModelService<TService>()
where TService : class
=> InvokeOnUIThread(cancellationToken => GetComponentModel().GetService<TService>());
protected static DTE GetDTE()
=> GetGlobalService<SDTE, DTE>();
protected static IComponentModel GetComponentModel()
=> GetGlobalService<SComponentModel, IComponentModel>();
protected static bool IsCommandAvailable(string commandName)
=> GetDTE().Commands.Item(commandName).IsAvailable;
protected static void ExecuteCommand(string commandName, string args = "")
{
var task = Task.Run(() => GetDTE().ExecuteCommand(commandName, args));
task.Wait(Helper.HangMitigatingTimeout);
}
/// <summary>
/// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT).
/// </summary>
protected static void WaitForApplicationIdle(TimeSpan timeout)
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
=> CurrentApplicationDispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle).Wait(timeout);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
protected static void WaitForSystemIdle()
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
=> CurrentApplicationDispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
// Ensure InProcComponents live forever
public override object? InitializeLifetimeService() => null;
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DebuggerDiagnosticFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal class DebuggerDiagnosticFormatter : DiagnosticFormatter
{
public override string Format(Diagnostic diagnostic, IFormatProvider? formatter = null)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
var culture = formatter as CultureInfo;
return string.Format(formatter, "{0}: {1}",
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
}
internal static new readonly DebuggerDiagnosticFormatter Instance = new DebuggerDiagnosticFormatter();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal class DebuggerDiagnosticFormatter : DiagnosticFormatter
{
public override string Format(Diagnostic diagnostic, IFormatProvider? formatter = null)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
var culture = formatter as CultureInfo;
return string.Format(formatter, "{0}: {1}",
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
}
internal static new readonly DebuggerDiagnosticFormatter Instance = new DebuggerDiagnosticFormatter();
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
public class SuggestionModeCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(CSharpSuggestionModeCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstExplicitArgument()
{
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (int x, i $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstImplicitArgument()
{
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (x, i $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstImplicitArgumentInMethodCall()
{
var markup = @"class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar((x, i $$
}
}
";
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstExplicitArgumentInMethodCall()
{
var markup = @"class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar((int x, i $$
}
}
";
// Could be a deconstruction expression
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateTypeExpected1()
{
var markup = @"using System;
class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar($$
}
}
";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateTypeExpected2()
=> await VerifyBuilderAsync(AddUsingDirectives("using System;", AddInsideMethod(@"Func<int, int, int> f = $$")));
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectInitializerDelegateType()
{
var markup = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public Func<int> myfunc { get; set; }
}
class a
{
void goo()
{
var b = new Program() { myfunc = $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, WorkItem(817145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/817145"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitArrayInitializer()
{
var markup = @"using System;
class a
{
void goo()
{
Func<int, int>[] myfunc = new Func<int, int>[] { $$;
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerUnknownType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = new [] { $$;
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerKnownDelegateType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = new [] { x => 2 * x, $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorUnknownType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = true ? $$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorKnownDelegateType1()
{
var markup = @"using System;
class a
{
void goo()
{
var a = true ? x => x * 2 : $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorKnownDelegateType2()
{
var markup = @"using System;
class a
{
void goo()
{
Func<int, int> a = true ? $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverloadTakesADelegate1()
{
var markup = @"using System;
class a
{
void goo(int a) { }
void goo(Func<int, int> a) { }
void bar()
{
this.goo($$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverloadTakesDelegate2()
{
var markup = @"using System;
class a
{
void goo(int i, int a) { }
void goo(int i, Func<int, int> a) { }
void bar()
{
this.goo(1, $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitCastToDelegate()
{
var markup = @"using System;
class a
{
void bar()
{
(Func<int, int>) ($$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(860580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860580")]
public async Task ReturnStatement()
{
var markup = @"using System;
class a
{
Func<int, int> bar()
{
return $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType1()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {$$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType2()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {$$ 1, 2 };
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType3()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {Name = 1, $$ };
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInFromClause()
{
var markup = @"using System;
using System.Linq;
class a
{
int bar()
{
var q = from $$
}
}";
await VerifyBuilderAsync(markup.ToString());
}
[WorkItem(823968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/823968")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInJoinClause()
{
var markup = @"using System;
using System.Linq;
using System.Collections.Generic;
class a
{
int bar()
{
var list = new List<int>();
var q = from a in list
join $$
}
}";
await VerifyBuilderAsync(markup.ToString());
}
[WorkItem(544290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544290")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$, e) => { });
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteNestedParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(((a$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpressionInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInObjectCreation()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program x = new P$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInArrayCreation()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program[] x = new $$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInArrayCreation2()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program[] x = new Pr$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleExpressionInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a$$, b)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleExpressionInVarDeclaration2()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteLambdaInActionDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a$$, b)
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInActionDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a$$, b: b)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInActionDeclaration2()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a: a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a: a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderForLinqExpression()
{
var markup = @"using System;
using System.Linq.Expressions;
public class Class
{
public void Goo(Expression<Action<int>> arg)
{
Goo($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInTypeParameter()
{
var markup = @"using System;
using System.Linq.Expressions;
public class Class
{
public void Goo(Expression<Action<int>> arg)
{
Enumerable.Empty<$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(611477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611477")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodFaultTolerance()
{
var markup = @"using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Outer
{
public struct ImmutableArray<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public static class ReadOnlyArrayExtensions
{
public static ImmutableArray<TResult> Select<T, TResult>(this ImmutableArray<T> array, Func<T, TResult> selector)
{
throw new NotImplementedException();
}
}
namespace Inner
{
class Program
{
static void Main(string[] args)
{
args.Select($$
}
}
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(834609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaWithAutomaticBraceCompletion()
{
var markup = @"using System;
using System;
public class Class
{
public void Goo()
{
EventHandler h = (s$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThisConstructorInitializer()
{
var markup = @"using System;
class X
{
X(Func<X> x) : this($$) { }
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseConstructorInitializer()
{
var markup = @"using System;
class B
{
public B(Func<B> x) {}
}
class D : B
{
D() : base($$) { }
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(887842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887842")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PreprocessorExpression()
{
var markup = @"class C
{
#if $$
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(967254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/967254")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerAfterNew()
{
var markup = @"using System;
class a
{
void goo()
{
int[] a = new $$;
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceDeclaration_Unqualified()
{
var markup = @"namespace $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceDeclaration_Qualified()
{
var markup = @"namespace A.$$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FileScopedNamespaceDeclaration_Unqualified()
{
var markup = @"namespace $$;";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FileScopedNamespaceDeclaration_Qualified()
{
var markup = @"namespace A.$$;";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialClassName()
{
var markup = @"partial class $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialStructName()
{
var markup = @"partial struct $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialInterfaceName()
{
var markup = @"partial interface $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnwrapParamsArray()
{
var markup = @"
using System;
class C {
C(params Action<int>[] a) {
new C($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoNotUnwrapRegularArray()
{
var markup = @"
using System;
class C {
C(Action<int>[] a) {
new C($$
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(47662, "https://github.com/dotnet/roslyn/issues/47662")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaExpressionInImplicitObjectCreation()
{
var markup = @"
using System;
class C {
C(Action<int> a) {
C c = new($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderWhenDelegateInferredRightOfDotInInvocation()
{
var markup = @"
class C {
Action a = Task.$$
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderInTypeArgument()
{
var markup = @"
namespace ConsoleApplication1
{
class Program
{
class N { }
static void Main(string[] args)
{
Program.N n = Load<Program.$$
}
static T Load<T>() => default(T);
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(16176, "https://github.com/dotnet/roslyn/issues/16176")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderForLambdaAfterNew()
{
var markup = @"
class C {
Action a = new $$
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AsyncLambda()
{
var markup = @"
using System;
using System.Threading.Tasks;
class Program
{
public void B(Func<int, int, Task<int>> f) { }
void A()
{
B(async($$";
await VerifyBuilderAsync(markup);
}
[WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AsyncLambdaAfterComma()
{
var markup = @"
using System;
using System.Threading.Tasks;
class Program
{
public void B(Func<int, int, Task<int>> f) { }
void A()
{
B(async(p1, $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod1()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod2()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$)
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod3()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod4()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$)
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod5()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$))
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod6()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar((a, $$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod7()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(async (a$$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithNonDelegateExtensionAndInstanceMethod1()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, int val)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$
}
}
";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInDeclarationPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is int o$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInDeclarationPattern2()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is System.Collections.Generic.List<int> an$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInRecursivePattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is { P: 1 } o$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInPropertyPattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is { P: int o$$ })
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInAndPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 and int a$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInAndOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is (int or 1) and int a$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInSwitchStatement()
{
var markup = @"
class C
{
void M()
{
var e = new object();
switch (e)
{
case int o$$
}
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInSwitchExpression()
{
var markup = @"
class C
{
void M()
{
var e = new object();
var result = e switch
{
int o$$
}
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Declaration()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is not int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Declaration2()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is not (1 and int o$$))
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Recursive()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is not { P: 1 } o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 or int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInAndOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 or int and int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInRecursiveOrPattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is null or { P: 1 } o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar)
{
var markup = $@"
using System;
interface Foo
{{
bool Bar() => true;
}}
class P
{{
void M(Foo f)
{{
f.Bar({(hasTypedChar ? "s" : "")}$$
}}
}}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLambda, bool hasTypedChar)
{
var overload = isLambda
? "bool Bar(Func<int, bool> predicate) => true;"
: "bool Bar(int x) => true;";
var markup = $@"
using System;
interface Foo
{{
bool Bar() => true;
{overload}
}}
class P
{{
void M(Foo f)
{{
f.Bar({(hasTypedChar ? "s" : "")}$$
}}
}}";
if (isLambda)
{
await VerifyBuilderAsync(markup);
}
else
{
await VerifyNotBuilderAsync(markup);
}
}
[InlineData("params string[] x")]
[InlineData("string x = null, string y = null")]
[InlineData("string x = null, string y = null, params string[] z")]
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(49656, "https://github.com/dotnet/roslyn/issues/49656")]
public async Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList)
{
var markup = $@"
using System;
interface Foo
{{
bool Bar({overloadParameterList}) => true;
bool Bar(Func<int, bool> predicate) => true;
}}
class P
{{
void M(Foo f)
{{
f.Bar($$)
}}
}}";
await VerifyBuilderAsync(markup);
}
private async Task VerifyNotBuilderAsync(string markup)
=> await VerifyWorkerAsync(markup, isBuilder: false);
private async Task VerifyBuilderAsync(string markup)
=> await VerifyWorkerAsync(markup, isBuilder: true);
private async Task VerifyWorkerAsync(string markup, bool isBuilder)
{
MarkupTestFile.GetPosition(markup, out var code, out int position);
using (var workspaceFixture = new CSharpTestWorkspaceFixture())
{
workspaceFixture.GetWorkspace(ExportProvider);
var document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular);
await CheckResultsAsync(document1, position, isBuilder);
if (await CanUseSpeculativeSemanticModelAsync(document1, position))
{
var document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate: false);
await CheckResultsAsync(document2, position, isBuilder);
}
}
}
private async Task CheckResultsAsync(Document document, int position, bool isBuilder)
{
var triggerInfos = new List<CompletionTrigger>();
triggerInfos.Add(CompletionTrigger.CreateInsertionTrigger('a'));
triggerInfos.Add(CompletionTrigger.Invoke);
triggerInfos.Add(CompletionTrigger.CreateDeletionTrigger('z'));
var service = GetCompletionService(document.Project);
var provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet<string>.Empty));
foreach (var triggerInfo in triggerInfos)
{
var completionList = await service.GetTestAccessor().GetContextAsync(
provider, document, position, triggerInfo,
options: null, cancellationToken: CancellationToken.None);
if (isBuilder)
{
Assert.NotNull(completionList);
Assert.True(completionList.SuggestionModeItem != null, "Expecting a suggestion mode, but none was present");
}
else
{
if (completionList != null)
{
Assert.True(completionList.SuggestionModeItem == null, "group.Builder == " + (completionList.SuggestionModeItem != null ? completionList.SuggestionModeItem.DisplayText : "null"));
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
public class SuggestionModeCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(CSharpSuggestionModeCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstExplicitArgument()
{
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (int x, i $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstImplicitArgument()
{
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (x, i $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstImplicitArgumentInMethodCall()
{
var markup = @"class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar((x, i $$
}
}
";
// The right-hand-side parses like a possible deconstruction or tuple type
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterFirstExplicitArgumentInMethodCall()
{
var markup = @"class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar((int x, i $$
}
}
";
// Could be a deconstruction expression
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateTypeExpected1()
{
var markup = @"using System;
class c
{
private void bar(Func<int, int, bool> f) { }
private void goo()
{
bar($$
}
}
";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateTypeExpected2()
=> await VerifyBuilderAsync(AddUsingDirectives("using System;", AddInsideMethod(@"Func<int, int, int> f = $$")));
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectInitializerDelegateType()
{
var markup = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public Func<int> myfunc { get; set; }
}
class a
{
void goo()
{
var b = new Program() { myfunc = $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, WorkItem(817145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/817145"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitArrayInitializer()
{
var markup = @"using System;
class a
{
void goo()
{
Func<int, int>[] myfunc = new Func<int, int>[] { $$;
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerUnknownType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = new [] { $$;
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerKnownDelegateType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = new [] { x => 2 * x, $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorUnknownType()
{
var markup = @"using System;
class a
{
void goo()
{
var a = true ? $$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorKnownDelegateType1()
{
var markup = @"using System;
class a
{
void goo()
{
var a = true ? x => x * 2 : $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TernaryOperatorKnownDelegateType2()
{
var markup = @"using System;
class a
{
void goo()
{
Func<int, int> a = true ? $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverloadTakesADelegate1()
{
var markup = @"using System;
class a
{
void goo(int a) { }
void goo(Func<int, int> a) { }
void bar()
{
this.goo($$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverloadTakesDelegate2()
{
var markup = @"using System;
class a
{
void goo(int i, int a) { }
void goo(int i, Func<int, int> a) { }
void bar()
{
this.goo(1, $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitCastToDelegate()
{
var markup = @"using System;
class a
{
void bar()
{
(Func<int, int>) ($$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(860580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860580")]
public async Task ReturnStatement()
{
var markup = @"using System;
class a
{
Func<int, int> bar()
{
return $$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType1()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {$$
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType2()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {$$ 1, 2 };
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInAnonymousType3()
{
var markup = @"using System;
class a
{
int bar()
{
var q = new {Name = 1, $$ };
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInFromClause()
{
var markup = @"using System;
using System.Linq;
class a
{
int bar()
{
var q = from $$
}
}";
await VerifyBuilderAsync(markup.ToString());
}
[WorkItem(823968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/823968")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderInJoinClause()
{
var markup = @"using System;
using System.Linq;
using System.Collections.Generic;
class a
{
int bar()
{
var list = new List<int>();
var q = from a in list
join $$
}
}";
await VerifyBuilderAsync(markup.ToString());
}
[WorkItem(544290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544290")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$, e) => { });
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteNestedParenthesizedLambdaArgument()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(((a$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpressionInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInObjectCreation()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program x = new P$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInArrayCreation()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program[] x = new $$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")]
public async Task TestInArrayCreation2()
{
var markup = @"using System;
class Program
{
static void Main()
{
Program[] x = new Pr$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleExpressionInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a$$, b)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleExpressionInVarDeclaration2()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteLambdaInActionDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a$$, b)
}
}";
await VerifyBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInActionDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a$$, b: b)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInActionDeclaration2()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
System.Action x = (a: a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleWithNamesInVarDeclaration()
{
var markup = @"using System;
class Program
{
static void Main(string[] args)
{
var x = (a: a, b$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BuilderForLinqExpression()
{
var markup = @"using System;
using System.Linq.Expressions;
public class Class
{
public void Goo(Expression<Action<int>> arg)
{
Goo($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotInTypeParameter()
{
var markup = @"using System;
using System.Linq.Expressions;
public class Class
{
public void Goo(Expression<Action<int>> arg)
{
Enumerable.Empty<$$
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(611477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611477")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodFaultTolerance()
{
var markup = @"using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Outer
{
public struct ImmutableArray<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public static class ReadOnlyArrayExtensions
{
public static ImmutableArray<TResult> Select<T, TResult>(this ImmutableArray<T> array, Func<T, TResult> selector)
{
throw new NotImplementedException();
}
}
namespace Inner
{
class Program
{
static void Main(string[] args)
{
args.Select($$
}
}
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(834609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaWithAutomaticBraceCompletion()
{
var markup = @"using System;
using System;
public class Class
{
public void Goo()
{
EventHandler h = (s$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThisConstructorInitializer()
{
var markup = @"using System;
class X
{
X(Func<X> x) : this($$) { }
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseConstructorInitializer()
{
var markup = @"using System;
class B
{
public B(Func<B> x) {}
}
class D : B
{
D() : base($$) { }
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(887842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887842")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PreprocessorExpression()
{
var markup = @"class C
{
#if $$
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(967254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/967254")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ImplicitArrayInitializerAfterNew()
{
var markup = @"using System;
class a
{
void goo()
{
int[] a = new $$;
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceDeclaration_Unqualified()
{
var markup = @"namespace $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceDeclaration_Qualified()
{
var markup = @"namespace A.$$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FileScopedNamespaceDeclaration_Unqualified()
{
var markup = @"namespace $$;";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FileScopedNamespaceDeclaration_Qualified()
{
var markup = @"namespace A.$$;";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialClassName()
{
var markup = @"partial class $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialStructName()
{
var markup = @"partial struct $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PartialInterfaceName()
{
var markup = @"partial interface $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnwrapParamsArray()
{
var markup = @"
using System;
class C {
C(params Action<int>[] a) {
new C($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoNotUnwrapRegularArray()
{
var markup = @"
using System;
class C {
C(Action<int>[] a) {
new C($$
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(47662, "https://github.com/dotnet/roslyn/issues/47662")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaExpressionInImplicitObjectCreation()
{
var markup = @"
using System;
class C {
C(Action<int> a) {
C c = new($$
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderWhenDelegateInferredRightOfDotInInvocation()
{
var markup = @"
class C {
Action a = Task.$$
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderInTypeArgument()
{
var markup = @"
namespace ConsoleApplication1
{
class Program
{
class N { }
static void Main(string[] args)
{
Program.N n = Load<Program.$$
}
static T Load<T>() => default(T);
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(16176, "https://github.com/dotnet/roslyn/issues/16176")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotBuilderForLambdaAfterNew()
{
var markup = @"
class C {
Action a = new $$
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AsyncLambda()
{
var markup = @"
using System;
using System.Threading.Tasks;
class Program
{
public void B(Func<int, int, Task<int>> f) { }
void A()
{
B(async($$";
await VerifyBuilderAsync(markup);
}
[WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AsyncLambdaAfterComma()
{
var markup = @"
using System;
using System.Threading.Tasks;
class Program
{
public void B(Func<int, int, Task<int>> f) { }
void A()
{
B(async(p1, $$";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod1()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod2()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$)
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod3()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod4()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$)
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod5()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(($$))
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod6()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar((a, $$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithExtensionAndInstanceMethod7()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, Action<int> action)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(async (a$$
}
}
";
await VerifyBuilderAsync(markup);
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithNonDelegateExtensionAndInstanceMethod1()
{
var markup = @"
using System;
public sealed class Goo
{
public void Bar()
{
}
}
public static class GooExtensions
{
public static void Bar(this Goo goo, int val)
{
}
}
public static class Repro
{
public static void ReproMethod(Goo goo)
{
goo.Bar(a$$
}
}
";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInDeclarationPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is int o$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInDeclarationPattern2()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is System.Collections.Generic.List<int> an$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInRecursivePattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is { P: 1 } o$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInPropertyPattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is { P: int o$$ })
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInAndPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 and int a$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInAndOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is (int or 1) and int a$$)
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInSwitchStatement()
{
var markup = @"
class C
{
void M()
{
var e = new object();
switch (e)
{
case int o$$
}
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestInSwitchExpression()
{
var markup = @"
class C
{
void M()
{
var e = new object();
var result = e switch
{
int o$$
}
}
}";
await VerifyBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Declaration()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is not int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Declaration2()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is not (1 and int o$$))
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInNotPattern_Recursive()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is not { P: 1 } o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 or int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInAndOrPattern()
{
var markup = @"
class C
{
void M()
{
var e = new object();
if (e is 1 or int and int o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestMissingInRecursiveOrPattern()
{
var markup = @"
class C
{
int P { get; }
void M(C test)
{
if (test is null or { P: 1 } o$$)
}
}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar)
{
var markup = $@"
using System;
interface Foo
{{
bool Bar() => true;
}}
class P
{{
void M(Foo f)
{{
f.Bar({(hasTypedChar ? "s" : "")}$$
}}
}}";
await VerifyNotBuilderAsync(markup);
}
[WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")]
[Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLambda, bool hasTypedChar)
{
var overload = isLambda
? "bool Bar(Func<int, bool> predicate) => true;"
: "bool Bar(int x) => true;";
var markup = $@"
using System;
interface Foo
{{
bool Bar() => true;
{overload}
}}
class P
{{
void M(Foo f)
{{
f.Bar({(hasTypedChar ? "s" : "")}$$
}}
}}";
if (isLambda)
{
await VerifyBuilderAsync(markup);
}
else
{
await VerifyNotBuilderAsync(markup);
}
}
[InlineData("params string[] x")]
[InlineData("string x = null, string y = null")]
[InlineData("string x = null, string y = null, params string[] z")]
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(49656, "https://github.com/dotnet/roslyn/issues/49656")]
public async Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList)
{
var markup = $@"
using System;
interface Foo
{{
bool Bar({overloadParameterList}) => true;
bool Bar(Func<int, bool> predicate) => true;
}}
class P
{{
void M(Foo f)
{{
f.Bar($$)
}}
}}";
await VerifyBuilderAsync(markup);
}
private async Task VerifyNotBuilderAsync(string markup)
=> await VerifyWorkerAsync(markup, isBuilder: false);
private async Task VerifyBuilderAsync(string markup)
=> await VerifyWorkerAsync(markup, isBuilder: true);
private async Task VerifyWorkerAsync(string markup, bool isBuilder)
{
MarkupTestFile.GetPosition(markup, out var code, out int position);
using (var workspaceFixture = new CSharpTestWorkspaceFixture())
{
workspaceFixture.GetWorkspace(ExportProvider);
var document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular);
await CheckResultsAsync(document1, position, isBuilder);
if (await CanUseSpeculativeSemanticModelAsync(document1, position))
{
var document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate: false);
await CheckResultsAsync(document2, position, isBuilder);
}
}
}
private async Task CheckResultsAsync(Document document, int position, bool isBuilder)
{
var triggerInfos = new List<CompletionTrigger>();
triggerInfos.Add(CompletionTrigger.CreateInsertionTrigger('a'));
triggerInfos.Add(CompletionTrigger.Invoke);
triggerInfos.Add(CompletionTrigger.CreateDeletionTrigger('z'));
var service = GetCompletionService(document.Project);
var provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet<string>.Empty));
foreach (var triggerInfo in triggerInfos)
{
var completionList = await service.GetTestAccessor().GetContextAsync(
provider, document, position, triggerInfo,
options: null, cancellationToken: CancellationToken.None);
if (isBuilder)
{
Assert.NotNull(completionList);
Assert.True(completionList.SuggestionModeItem != null, "Expecting a suggestion mode, but none was present");
}
else
{
if (completionList != null)
{
Assert.True(completionList.SuggestionModeItem == null, "group.Builder == " + (completionList.SuggestionModeItem != null ? completionList.SuggestionModeItem.DisplayText : "null"));
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArrayElementReferenceExpression.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.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_ConstantIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String())
Dim a = args(0)'BIND:"args(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_NonConstantIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(), x As Integer)
Dim a = args(x)'BIND:"args(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_FunctionCallArrayReference()
Dim source = <![CDATA[
Class C
Public Sub F()
Dim a = F2()(0)'BIND:"F2()(0)"
End Sub
Public Function F2() As String()
Return Nothing
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'F2()(0)')
Array reference:
IInvocationOperation ( Function C.F2() As System.String()) (OperationKind.Invocation, Type: System.String()) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_ConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,))
Dim a = args(0, 1)'BIND:"args(0, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0, 1)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_NonConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,), x As Integer, y As Integer)
Dim a = args(x, y)'BIND:"args(x, y)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x, y)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_InvocationInIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,), x As Integer)
Dim a = args(x, F2)'BIND:"args(x, F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x, F2)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArray_ConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()())
Dim a = args(0)(1)'BIND:"args(0)(1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0)(1)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String()) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArray_NonConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()())
Dim x As Integer = 0
Dim a = args(x)(F2)'BIND:"args(x)(F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)(F2)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String()) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()()) (Syntax: 'args')
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Indices(1):
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArrayOfMultidimensionalArrays()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()(,))
Dim x As Integer = 0
Dim a = args(x)(0, F2)'BIND:"args(x)(0, F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)(0, F2)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String(,)) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()(,)) (Syntax: 'args')
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ImplicitConversionInIndexExpression()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(), b As Byte)
Dim a = args(b)'BIND:"args(b)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(b)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'b')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), o As Object)
Dim a = args(DirectCast(o, Integer))'BIND:"args(DirectCast(o, Integer))"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(Direct ... , Integer))')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: 'DirectCast(o, Integer)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ImplicitUserDefinedConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitUserDefinedConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(CType(c, Integer))'BIND:"args(CType(c, Integer))"
End Sub
Public Shared Narrowing Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(CType(c, Integer))')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Explicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32) (Syntax: 'CType(c, Integer)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitConversionInArrayReference()
Dim source = <![CDATA[
Class C
Public Sub F(o As Object, x As Integer)
Dim a = DirectCast(o, String())(x)'BIND:"DirectCast(o, String())(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'DirectCast( ... tring())(x)')
Array reference:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String()) (Syntax: 'DirectCast(o, String())')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NoConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C' cannot be converted to 'Integer'.
Dim a = args(c)'BIND:"args(c)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_MissingExplicitCastInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
Public Shared Narrowing Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Explicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'C' to 'Integer'.
Dim a = args(c)'BIND:"args(c)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NoIndices()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args()'BIND:"args()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args()')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30105: Number of indices is less than the number of dimensions of the indexed array.
Dim a = args()'BIND:"args()"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_BadIndexing()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(c As C)
Dim a = c(0)'BIND:"c(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c(0)')
Children(2):
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30367: Class 'C' cannot be indexed because it has no default property.
Dim a = c(0)'BIND:"c(0)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_BadIndexCount()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0, 0)'BIND:"args(0, 0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0, 0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
Dim a = args(0, 0)'BIND:"args(0, 0)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_ExtraElementAccessOperator()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As C())
Dim a = args(0)()'BIND:"args(0)()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(0)()')
Children(1):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: C, IsInvalid) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: C(), IsInvalid) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30367: Class 'C' cannot be indexed because it has no default property.
Dim a = args(0)()'BIND:"args(0)()"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_IndexErrorExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F()
Dim a = ErrorExpression(0)'BIND:"ErrorExpression(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression(0)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression')
Children(0)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30451: 'ErrorExpression' is not declared. It may be inaccessible due to its protection level.
Dim a = ErrorExpression(0)'BIND:"ErrorExpression(0)"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingValue()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0,)'BIND:"args(0,)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0,)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '')
Children(1):
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
Dim a = args(0,)'BIND:"args(0,)"
~~~~
BC30491: Expression does not produce a value.
Dim a = args(0,)'BIND:"args(0,)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingParens()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args('BIND:"args("
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30198: ')' expected.
Dim a = args('BIND:"args("
~
BC30201: Expression expected.
Dim a = args('BIND:"args("
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingParensAfterIndex()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0'BIND:"args(0"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30198: ')' expected.
Dim a = args(0'BIND:"args(0"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_DeeplyNestedParameterReference()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), x As Integer, y As Integer)
Dim a = args(y)()()()(x)'BIND:"args(y)()()()(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()()(x)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()()')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: System.Char, IsInvalid) (Syntax: 'args(y)()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'args(y)')
Children(1):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(y)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'index' of 'Public Overloads ReadOnly Default Property Chars(index As Integer) As Char'.
Dim a = args(y)()()()(x)'BIND:"args(y)()()()(x)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NamedArgumentForArray()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), x As Integer)
Dim a = args(name:=x)'BIND:"args(name:=x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(name:=x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30075: Named arguments are not valid as array subscripts.
Dim a = args(name:=x)'BIND:"args(name:=x)"
~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_NegativeIndexExpression()
Dim source = <![CDATA[
Class C
Public Sub F(args As String())
Dim a = args(-1)'BIND:"args(-1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(-1)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -1) (Syntax: '-1')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_NoControlFlow()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(,), ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal result1 As Integer, ByVal result2 As Integer)'BIND:"Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(,), ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal result1 As Integer, ByVal result2 As Integer)"
result1 = a1(i1)
result2 = a2(i2, i3)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = a1(i1)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result1 = a1(i1)')
Left:
IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result1')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a1(i1)')
Array reference:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a1')
Indices(1):
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result2 = a2(i2, i3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result2 = a2(i2, i3)')
Left:
IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result2')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a2(i2, i3)')
Array reference:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a2')
Indices(2):
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInArrayReference()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(), ByVal i As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(), ByVal i As Integer, ByVal result As Integer)"
result = If(a1, a2)(i)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'a1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = If(a1, a2)(i)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = If(a1, a2)(i)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'If(a1, a2)(i)')
Array reference:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'If(a1, a2)')
Indices(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInFirstIndex()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Byte, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Byte, ByVal result As Integer)"
result = a(If(i1, i2), j)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... i1, i2), j)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... i1, i2), j)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(If(i1, i2), j)')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'j')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInSecondIndex()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Integer, ByVal result As Integer)"
result = a(j, If(i1, i2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... If(i1, i2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... If(i1, i2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(j, If(i1, i2))')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInMultipleIndices()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer)"
result = a(If(i1, i2), If(j1, j2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3] [5]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'j1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... If(j1, j2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... If(j1, j2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(If(i1, i2 ... If(j1, j2))')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(j1, j2)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInArrayReferenceAndIndices()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(,), ByVal a2 As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a1 As Integer(,), ByVal a2 As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer)"
result = If(a1, a2)(If(i1, i2), If(j1, j2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [4] [6]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a1')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [3]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
Entering: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B8]
Entering: {R4}
.locals {R4}
{
CaptureIds: [5]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'j1')
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Leaving: {R4}
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B11]
Leaving: {R4}
}
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = If ... If(j1, j2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = If ... If(j1, j2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'If(a1, a2)( ... If(j1, j2))')
Array reference:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'If(a1, a2)')
Indices(2):
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(j1, j2)')
Next (Regular) Block[B12]
Leaving: {R1}
}
Block[B12] - Exit
Predecessors: [B11]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_ConstantIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String())
Dim a = args(0)'BIND:"args(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_NonConstantIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(), x As Integer)
Dim a = args(x)'BIND:"args(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_SingleDimensionArray_FunctionCallArrayReference()
Dim source = <![CDATA[
Class C
Public Sub F()
Dim a = F2()(0)'BIND:"F2()(0)"
End Sub
Public Function F2() As String()
Return Nothing
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'F2()(0)')
Array reference:
IInvocationOperation ( Function C.F2() As System.String()) (OperationKind.Invocation, Type: System.String()) (Syntax: 'F2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_ConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,))
Dim a = args(0, 1)'BIND:"args(0, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0, 1)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_NonConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,), x As Integer, y As Integer)
Dim a = args(x, y)'BIND:"args(x, y)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x, y)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_MultiDimensionArray_InvocationInIndex()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(,), x As Integer)
Dim a = args(x, F2)'BIND:"args(x, F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x, F2)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(,)) (Syntax: 'args')
Indices(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArray_ConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()())
Dim a = args(0)(1)'BIND:"args(0)(1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(0)(1)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String()) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArray_NonConstantIndices()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()())
Dim x As Integer = 0
Dim a = args(x)(F2)'BIND:"args(x)(F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)(F2)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String()) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()()) (Syntax: 'args')
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Indices(1):
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_JaggedArrayOfMultidimensionalArrays()
Dim source = <![CDATA[
Class C
Public Sub F(args As String()(,))
Dim x As Integer = 0
Dim a = args(x)(0, F2)'BIND:"args(x)(0, F2)"
End Sub
Public Function F2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(x)(0, F2)')
Array reference:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String(,)) (Syntax: 'args(x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()(,)) (Syntax: 'args')
Indices(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IInvocationOperation ( Function C.F2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F2')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ImplicitConversionInIndexExpression()
Dim source = <![CDATA[
Class C
Public Sub F(args As String(), b As Byte)
Dim a = args(b)'BIND:"args(b)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(b)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'b')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), o As Object)
Dim a = args(DirectCast(o, Integer))'BIND:"args(DirectCast(o, Integer))"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(Direct ... , Integer))')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: 'DirectCast(o, Integer)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ImplicitUserDefinedConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitUserDefinedConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(CType(c, Integer))'BIND:"args(CType(c, Integer))"
End Sub
Public Shared Narrowing Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(CType(c, Integer))')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Explicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32) (Syntax: 'CType(c, Integer)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_ExplicitConversionInArrayReference()
Dim source = <![CDATA[
Class C
Public Sub F(o As Object, x As Integer)
Dim a = DirectCast(o, String())(x)'BIND:"DirectCast(o, String())(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'DirectCast( ... tring())(x)')
Array reference:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String()) (Syntax: 'DirectCast(o, String())')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NoConversionInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C' cannot be converted to 'Integer'.
Dim a = args(c)'BIND:"args(c)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_MissingExplicitCastInIndexExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args(c)'BIND:"args(c)"
End Sub
Public Shared Narrowing Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(c)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Explicit(c As C) As System.Int32) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(c As C) As System.Int32)
Operand:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'C' to 'Integer'.
Dim a = args(c)'BIND:"args(c)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NoIndices()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), c As C)
Dim a = args()'BIND:"args()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args()')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30105: Number of indices is less than the number of dimensions of the indexed array.
Dim a = args()'BIND:"args()"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_BadIndexing()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(c As C)
Dim a = c(0)'BIND:"c(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'c(0)')
Children(2):
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30367: Class 'C' cannot be indexed because it has no default property.
Dim a = c(0)'BIND:"c(0)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_BadIndexCount()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0, 0)'BIND:"args(0, 0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0, 0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
Dim a = args(0, 0)'BIND:"args(0, 0)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_ExtraElementAccessOperator()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As C())
Dim a = args(0)()'BIND:"args(0)()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(0)()')
Children(1):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: C, IsInvalid) (Syntax: 'args(0)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: C(), IsInvalid) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30367: Class 'C' cannot be indexed because it has no default property.
Dim a = args(0)()'BIND:"args(0)()"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_IndexErrorExpression()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F()
Dim a = ErrorExpression(0)'BIND:"ErrorExpression(0)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression(0)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'ErrorExpression')
Children(0)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30451: 'ErrorExpression' is not declared. It may be inaccessible due to its protection level.
Dim a = ErrorExpression(0)'BIND:"ErrorExpression(0)"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingValue()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0,)'BIND:"args(0,)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0,)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '')
Children(1):
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
Dim a = args(0,)'BIND:"args(0,)"
~~~~
BC30491: Expression does not produce a value.
Dim a = args(0,)'BIND:"args(0,)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingParens()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args('BIND:"args("
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30198: ')' expected.
Dim a = args('BIND:"args("
~
BC30201: Expression expected.
Dim a = args('BIND:"args("
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_MissingParensAfterIndex()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String())
Dim a = args(0'BIND:"args(0"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(0')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30198: ')' expected.
Dim a = args(0'BIND:"args(0"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_SyntaxErrorInIndexer_DeeplyNestedParameterReference()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), x As Integer, y As Integer)
Dim a = args(y)()()()(x)'BIND:"args(y)()()()(x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()()(x)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()()')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'args(y)()()')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: System.Char, IsInvalid) (Syntax: 'args(y)()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'args(y)')
Children(1):
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(y)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'index' of 'Public Overloads ReadOnly Default Property Chars(index As Integer) As Char'.
Dim a = args(y)()()()(x)'BIND:"args(y)()()()(x)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReferenceError_NamedArgumentForArray()
Dim source = <![CDATA[
Option Strict On
Class C
Public Sub F(args As String(), x As Integer)
Dim a = args(name:=x)'BIND:"args(name:=x)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String, IsInvalid) (Syntax: 'args(name:=x)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String(), IsInvalid) (Syntax: 'args')
Indices(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30075: Named arguments are not valid as array subscripts.
Dim a = args(name:=x)'BIND:"args(name:=x)"
~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(22006, "https://github.com/dotnet/roslyn/issues/22006")>
Public Sub ArrayElementReference_NegativeIndexExpression()
Dim source = <![CDATA[
Class C
Public Sub F(args As String())
Dim a = args(-1)'BIND:"args(-1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.String) (Syntax: 'args(-1)')
Array reference:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Indices(1):
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -1) (Syntax: '-1')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_NoControlFlow()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(,), ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal result1 As Integer, ByVal result2 As Integer)'BIND:"Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(,), ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal result1 As Integer, ByVal result2 As Integer)"
result1 = a1(i1)
result2 = a2(i2, i3)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = a1(i1)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result1 = a1(i1)')
Left:
IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result1')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a1(i1)')
Array reference:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a1')
Indices(1):
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result2 = a2(i2, i3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result2 = a2(i2, i3)')
Left:
IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result2')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a2(i2, i3)')
Array reference:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a2')
Indices(2):
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInArrayReference()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(), ByVal i As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a1 As Integer(), ByVal a2 As Integer(), ByVal i As Integer, ByVal result As Integer)"
result = If(a1, a2)(i)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'a1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = If(a1, a2)(i)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = If(a1, a2)(i)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'If(a1, a2)(i)')
Array reference:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'If(a1, a2)')
Indices(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInFirstIndex()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Byte, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Byte, ByVal result As Integer)"
result = a(If(i1, i2), j)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... i1, i2), j)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... i1, i2), j)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(If(i1, i2), j)')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'j')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInSecondIndex()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j As Integer, ByVal result As Integer)"
result = a(j, If(i1, i2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... If(i1, i2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... If(i1, i2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(j, If(i1, i2))')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInMultipleIndices()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer)"
result = a(If(i1, i2), If(j1, j2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3] [5]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'j1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a( ... If(j1, j2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = a( ... If(j1, j2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a(If(i1, i2 ... If(j1, j2))')
Array reference:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a')
Indices(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(j1, j2)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ArrayElementReference_ControlFlowInArrayReferenceAndIndices()
Dim source = <![CDATA[
Class C
Private Sub M(ByVal a1 As Integer(,), ByVal a2 As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer) 'BIND:"Private Sub M(ByVal a1 As Integer(,), ByVal a2 As Integer(,), ByVal i1 As Integer?, ByVal i2 As Integer, ByVal j1 As Integer?, ByVal j2 As Integer, ByVal result As Integer)"
result = If(a1, a2)(If(i1, i2), If(j1, j2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [4] [6]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'a1')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'a2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [3]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
Entering: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B8]
Entering: {R4}
.locals {R4}
{
CaptureIds: [5]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'j1')
Jump if True (Regular) to Block[B10]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Leaving: {R4}
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B11]
Leaving: {R4}
}
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = If ... If(j1, j2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = If ... If(j1, j2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'If(a1, a2)( ... If(j1, j2))')
Array reference:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'If(a1, a2)')
Indices(2):
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(j1, j2)')
Next (Regular) Block[B12]
Leaving: {R1}
}
Block[B12] - Exit
Predecessors: [B11]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingRoot.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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
/// <summary>
/// Interaction logic for ValueTrackingRoot.xaml
/// </summary>
internal partial class ValueTrackingRoot : UserControl
{
public string EmptyText => ServicesVSResources.Select_an_appropriate_symbol_to_start_value_tracking;
public ValueTrackingRoot()
{
InitializeComponent();
}
public void SetChild(FrameworkElement? child)
{
RootGrid.Children.Clear();
if (child is null)
{
EmptyTextMessage.Visibility = Visibility.Visible;
}
else
{
EmptyTextMessage.Visibility = Visibility.Collapsed;
RootGrid.Children.Add(child);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
/// <summary>
/// Interaction logic for ValueTrackingRoot.xaml
/// </summary>
internal partial class ValueTrackingRoot : UserControl
{
public string EmptyText => ServicesVSResources.Select_an_appropriate_symbol_to_start_value_tracking;
public ValueTrackingRoot()
{
InitializeComponent();
}
public void SetChild(FrameworkElement? child)
{
RootGrid.Children.Clear();
if (child is null)
{
EmptyTextMessage.Visibility = Visibility.Visible;
}
else
{
EmptyTextMessage.Visibility = Visibility.Collapsed;
RootGrid.Children.Add(child);
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Test/Core/Metadata/MetadataSignatureUnitTestHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal class MetadataSignatureUnitTestHelper
{
/// <summary>
/// Uses Reflection to verify that the specified member signatures are present in emitted metadata
/// </summary>
/// <param name="appDomainHost">Unit test AppDomain host</param>
/// <param name="expectedSignatures">Baseline signatures - use the Signature() factory method to create instances of SignatureDescription</param>
internal static void VerifyMemberSignatures(
IRuntimeEnvironment appDomainHost, params SignatureDescription[] expectedSignatures)
{
Assert.NotNull(expectedSignatures);
Assert.NotEmpty(expectedSignatures);
var succeeded = true;
var expected = new List<string>();
var actual = new List<string>();
foreach (var signature in expectedSignatures)
{
var expectedSignature = signature.ExpectedSignature;
if (!VerifyMemberSignatureHelper(
appDomainHost, signature.FullyQualifiedTypeName, signature.MemberName,
ref expectedSignature, out var actualSignatures))
{
succeeded = false;
}
expected.Add(expectedSignature);
actual.AddRange(actualSignatures);
}
if (!succeeded)
{
TriggerSignatureMismatchFailure(expected, actual);
}
}
/// <summary>
/// Uses Reflection to verify that the specified member signature is present in emitted metadata
/// </summary>
/// <param name="appDomainHost">Unit test AppDomain host</param>
/// <param name="fullyQualifiedTypeName">
/// Fully qualified type name for member
/// Names must be in format recognized by reflection
/// e.g. MyType<T>.MyNestedType<T, U> => MyType`1+MyNestedType`2
/// </param>
/// <param name="memberName">
/// Name of member on specified type whose signature needs to be verified
/// Names must be in format recognized by reflection
/// e.g. For explicitly implemented member - I1<string>.Method => I1<System.String>.Method
/// </param>
/// <param name="expectedSignature">
/// Baseline string for signature of specified member
/// Skip this argument to get an error message that shows all available signatures for specified member
/// This argument is passed by reference and it will be updated with a formatted form of the baseline signature for error reporting purposes
/// </param>
/// <param name="actualSignatures">List of found signatures matching member name</param>
/// <returns>True if a matching member signature was found, false otherwise</returns>
private static bool VerifyMemberSignatureHelper(
IRuntimeEnvironment appDomainHost, string fullyQualifiedTypeName, string memberName,
ref string expectedSignature, out List<string> actualSignatures)
{
Assert.False(string.IsNullOrWhiteSpace(fullyQualifiedTypeName), "'fullyQualifiedTypeName' can't be null or empty");
Assert.False(string.IsNullOrWhiteSpace(memberName), "'memberName' can't be null or empty");
var retVal = true;
actualSignatures = new List<string>();
var signatures = appDomainHost.GetMemberSignaturesFromMetadata(fullyQualifiedTypeName, memberName);
var signatureAssertText = "Signature(\"" + fullyQualifiedTypeName + "\", \"" + memberName + "\", \"{0}\"),";
if (!string.IsNullOrWhiteSpace(expectedSignature))
{
expectedSignature = expectedSignature.Replace("\"", "\\\"");
}
expectedSignature = string.Format(signatureAssertText, expectedSignature);
if (signatures.Count > 1)
{
var found = false;
foreach (var signature in signatures)
{
var actualSignature = signature.Replace("\"", "\\\"");
actualSignature = string.Format(signatureAssertText, actualSignature);
if (actualSignature == expectedSignature)
{
actualSignatures.Clear();
actualSignatures.Add(actualSignature);
found = true;
break;
}
else
{
actualSignatures.Add(actualSignature);
}
}
if (!found)
{
retVal = false;
}
}
else if (signatures.Count == 1)
{
var actualSignature = signatures.First().Replace("\"", "\\\"");
actualSignature = string.Format(signatureAssertText, actualSignature);
actualSignatures.Add(actualSignature);
if (expectedSignature != actualSignature)
{
retVal = false;
}
}
else
{
retVal = false;
}
return retVal;
}
/// <summary>
/// Triggers assert when expected and actual signatures don't match
/// </summary>
/// <param name="expectedSignatures">List of baseline signature strings</param>
/// <param name="actualSignatures">List of actually found signature strings</param>
private static void TriggerSignatureMismatchFailure(List<string> expectedSignatures, List<string> actualSignatures)
{
var expectedText = string.Empty;
var actualText = string.Empty;
var distinctSignatures = new HashSet<string>();
foreach (var signature in expectedSignatures)
{
// We need to preserve the order as well as prevent duplicates
if (!distinctSignatures.Contains(signature))
{
expectedText += "\n\t" + signature;
distinctSignatures.Add(signature);
}
}
distinctSignatures.Clear();
foreach (var signature in actualSignatures)
{
// We need to preserve the order as well as prevent duplicates
if (!distinctSignatures.Contains(signature))
{
actualText += "\n\t" + signature;
distinctSignatures.Add(signature);
}
}
expectedText = expectedText.TrimEnd(',');
actualText = actualText.TrimEnd(',');
var diffText = DiffUtil.DiffReport(expectedText, actualText);
Assert.True(false, "\n\nExpected:" + expectedText + "\n\nActual:" + actualText + "\n\nDifferences:\n" + diffText);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal class MetadataSignatureUnitTestHelper
{
/// <summary>
/// Uses Reflection to verify that the specified member signatures are present in emitted metadata
/// </summary>
/// <param name="appDomainHost">Unit test AppDomain host</param>
/// <param name="expectedSignatures">Baseline signatures - use the Signature() factory method to create instances of SignatureDescription</param>
internal static void VerifyMemberSignatures(
IRuntimeEnvironment appDomainHost, params SignatureDescription[] expectedSignatures)
{
Assert.NotNull(expectedSignatures);
Assert.NotEmpty(expectedSignatures);
var succeeded = true;
var expected = new List<string>();
var actual = new List<string>();
foreach (var signature in expectedSignatures)
{
var expectedSignature = signature.ExpectedSignature;
if (!VerifyMemberSignatureHelper(
appDomainHost, signature.FullyQualifiedTypeName, signature.MemberName,
ref expectedSignature, out var actualSignatures))
{
succeeded = false;
}
expected.Add(expectedSignature);
actual.AddRange(actualSignatures);
}
if (!succeeded)
{
TriggerSignatureMismatchFailure(expected, actual);
}
}
/// <summary>
/// Uses Reflection to verify that the specified member signature is present in emitted metadata
/// </summary>
/// <param name="appDomainHost">Unit test AppDomain host</param>
/// <param name="fullyQualifiedTypeName">
/// Fully qualified type name for member
/// Names must be in format recognized by reflection
/// e.g. MyType<T>.MyNestedType<T, U> => MyType`1+MyNestedType`2
/// </param>
/// <param name="memberName">
/// Name of member on specified type whose signature needs to be verified
/// Names must be in format recognized by reflection
/// e.g. For explicitly implemented member - I1<string>.Method => I1<System.String>.Method
/// </param>
/// <param name="expectedSignature">
/// Baseline string for signature of specified member
/// Skip this argument to get an error message that shows all available signatures for specified member
/// This argument is passed by reference and it will be updated with a formatted form of the baseline signature for error reporting purposes
/// </param>
/// <param name="actualSignatures">List of found signatures matching member name</param>
/// <returns>True if a matching member signature was found, false otherwise</returns>
private static bool VerifyMemberSignatureHelper(
IRuntimeEnvironment appDomainHost, string fullyQualifiedTypeName, string memberName,
ref string expectedSignature, out List<string> actualSignatures)
{
Assert.False(string.IsNullOrWhiteSpace(fullyQualifiedTypeName), "'fullyQualifiedTypeName' can't be null or empty");
Assert.False(string.IsNullOrWhiteSpace(memberName), "'memberName' can't be null or empty");
var retVal = true;
actualSignatures = new List<string>();
var signatures = appDomainHost.GetMemberSignaturesFromMetadata(fullyQualifiedTypeName, memberName);
var signatureAssertText = "Signature(\"" + fullyQualifiedTypeName + "\", \"" + memberName + "\", \"{0}\"),";
if (!string.IsNullOrWhiteSpace(expectedSignature))
{
expectedSignature = expectedSignature.Replace("\"", "\\\"");
}
expectedSignature = string.Format(signatureAssertText, expectedSignature);
if (signatures.Count > 1)
{
var found = false;
foreach (var signature in signatures)
{
var actualSignature = signature.Replace("\"", "\\\"");
actualSignature = string.Format(signatureAssertText, actualSignature);
if (actualSignature == expectedSignature)
{
actualSignatures.Clear();
actualSignatures.Add(actualSignature);
found = true;
break;
}
else
{
actualSignatures.Add(actualSignature);
}
}
if (!found)
{
retVal = false;
}
}
else if (signatures.Count == 1)
{
var actualSignature = signatures.First().Replace("\"", "\\\"");
actualSignature = string.Format(signatureAssertText, actualSignature);
actualSignatures.Add(actualSignature);
if (expectedSignature != actualSignature)
{
retVal = false;
}
}
else
{
retVal = false;
}
return retVal;
}
/// <summary>
/// Triggers assert when expected and actual signatures don't match
/// </summary>
/// <param name="expectedSignatures">List of baseline signature strings</param>
/// <param name="actualSignatures">List of actually found signature strings</param>
private static void TriggerSignatureMismatchFailure(List<string> expectedSignatures, List<string> actualSignatures)
{
var expectedText = string.Empty;
var actualText = string.Empty;
var distinctSignatures = new HashSet<string>();
foreach (var signature in expectedSignatures)
{
// We need to preserve the order as well as prevent duplicates
if (!distinctSignatures.Contains(signature))
{
expectedText += "\n\t" + signature;
distinctSignatures.Add(signature);
}
}
distinctSignatures.Clear();
foreach (var signature in actualSignatures)
{
// We need to preserve the order as well as prevent duplicates
if (!distinctSignatures.Contains(signature))
{
actualText += "\n\t" + signature;
distinctSignatures.Add(signature);
}
}
expectedText = expectedText.TrimEnd(',');
actualText = actualText.TrimEnd(',');
var diffText = DiffUtil.DiffReport(expectedText, actualText);
Assert.True(false, "\n\nExpected:" + expectedText + "\n\nActual:" + actualText + "\n\nDifferences:\n" + diffText);
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/DiscardSyntaxClassifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class DiscardSyntaxClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(
typeof(DiscardDesignationSyntax),
typeof(DiscardPatternSyntax),
typeof(ParameterSyntax),
typeof(IdentifierNameSyntax));
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (syntax.IsKind(SyntaxKind.DiscardDesignation) || syntax.IsKind(SyntaxKind.DiscardPattern))
{
result.Add(new ClassifiedSpan(syntax.Span, ClassificationTypeNames.Keyword));
return;
}
switch (syntax)
{
case ParameterSyntax parameter when parameter.Identifier.Text == "_":
var symbol = semanticModel.GetDeclaredSymbol(parameter, cancellationToken);
if (symbol?.IsDiscard == true)
{
result.Add(new ClassifiedSpan(parameter.Identifier.Span, ClassificationTypeNames.Keyword));
}
break;
case IdentifierNameSyntax identifierName when identifierName.Identifier.Text == "_":
var symbolInfo = semanticModel.GetSymbolInfo(identifierName, cancellationToken);
if (symbolInfo.Symbol?.Kind == SymbolKind.Discard)
{
result.Add(new ClassifiedSpan(syntax.Span, ClassificationTypeNames.Keyword));
}
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.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class DiscardSyntaxClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(
typeof(DiscardDesignationSyntax),
typeof(DiscardPatternSyntax),
typeof(ParameterSyntax),
typeof(IdentifierNameSyntax));
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (syntax.IsKind(SyntaxKind.DiscardDesignation) || syntax.IsKind(SyntaxKind.DiscardPattern))
{
result.Add(new ClassifiedSpan(syntax.Span, ClassificationTypeNames.Keyword));
return;
}
switch (syntax)
{
case ParameterSyntax parameter when parameter.Identifier.Text == "_":
var symbol = semanticModel.GetDeclaredSymbol(parameter, cancellationToken);
if (symbol?.IsDiscard == true)
{
result.Add(new ClassifiedSpan(parameter.Identifier.Span, ClassificationTypeNames.Keyword));
}
break;
case IdentifierNameSyntax identifierName when identifierName.Identifier.Text == "_":
var symbolInfo = semanticModel.GetSymbolInfo(identifierName, cancellationToken);
if (symbolInfo.Symbol?.Kind == SymbolKind.Discard)
{
result.Add(new ClassifiedSpan(syntax.Span, ClassificationTypeNames.Keyword));
}
break;
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/EditorFeatures/CSharp/ChangeSignature/CSharpChangeSignatureCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Implementation.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.ChangeSignature
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.ChangeSignature)]
internal class CSharpChangeSignatureCommandHandler : AbstractChangeSignatureCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeSignatureCommandHandler(IThreadingContext threadingContext)
: base(threadingContext)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.ChangeSignature
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.ChangeSignature)]
internal class CSharpChangeSignatureCommandHandler : AbstractChangeSignatureCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeSignatureCommandHandler(IThreadingContext threadingContext)
: base(threadingContext)
{
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems | <?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>Microsoft.CodeAnalysis.Shared</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentDictionaryExtensions.cs" Link="InternalUtilities\ConcurrentDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConfiguredYieldAwaitable.cs" Link="InternalUtilities\ConfiguredYieldAwaitable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Debug.cs" Link="InternalUtilities\Debug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumerableExtensions.cs" Link="InternalUtilities\EnumerableExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs" Link="InternalUtilities\ExceptionUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\IReadOnlySet.cs" Link="InternalUtilities\IReadOnlySet.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\KeyValuePairUtil.cs" Link="InternalUtilities\KeyValuePairUtil.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonCopyableAttribute.cs" Link="InternalUtilities\NonCopyableAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonDefaultableAttribute.cs" Link="InternalUtilities\NonDefaultableAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="InternalUtilities\NullableAttributes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReferenceEqualityComparer.cs" Link="InternalUtilities\ReferenceEqualityComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs" Link="InternalUtilities\RoslynString.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.cs" Link="InternalUtilities\SpecializedCollections.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SharedStopwatch.cs" Link="InternalUtilities\SharedStopwatch.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Collection.cs" Link="InternalUtilities\SpecializedCollections.Empty.Collection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.cs" Link="InternalUtilities\SpecializedCollections.Empty.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" Link="InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.List.cs" Link="InternalUtilities\SpecializedCollections.Empty.List.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Set.cs" Link="InternalUtilities\SpecializedCollections.Empty.Set.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringExtensions.cs" Link="InternalUtilities\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ValueTaskFactory.cs" Link="InternalUtilities\ValueTaskFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\VoidResult.cs" Link="InternalUtilities\VoidResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\YieldAwaitableExtensions.cs" Link="InternalUtilities\YieldAwaitableExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs" Link="Syntax\SyntaxTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ImmutableArrayExtensions.cs" Link="Collections\ImmutableArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\BitVector.cs" Link="Collections\BitVector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs" Link="InternalUtilities\Hash.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\GeneratedCodeUtilities.cs" Link="InternalUtilities\GeneratedCodeUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\IObjectWritable.cs" Link="Serialization\IObjectWritable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinder.cs" Link="Serialization\ObjectBinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinderSnapshot.cs" Link="Serialization\ObjectBinderSnapshot.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectReader.cs" Link="Serialization\ObjectReader.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectWriter.cs" Link="Serialization\ObjectWriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\SerializationThreadPool.cs" Link="Serialization\SerializationThreadPool.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SourceCodeKindExtensions.cs" Link="Utilities\Compiler\SourceCodeKindExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SpecialTypeExtensions.cs" Link="Extensions\Compiler\SpecialTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ArrayBuilderExtensions.cs">
<Link>Collections\ArrayBuilderExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\DictionaryExtensions.cs">
<Link>Collections\DictionaryExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\Boxes.cs">
<Link>Collections\Boxes.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\OrderPreservingMultiDictionary.cs">
<Link>Collections\OrderPreservingMultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\EncodedStringText.cs">
<Link>EncodedStringText.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\RelativePathResolver.cs">
<Link>FileSystem\RelativePathResolver.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\AssemblyIdentityUtils.cs">
<Link>InternalUtilities\AssemblyIdentityUtils.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\BitArithmeticUtilities.cs">
<Link>InternalUtilities\BitArithmeticUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ArrayExtensions.cs">
<Link>InternalUtilities\ArrayExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\CompilerOptionParseUtilities.cs">
<Link>InternalUtilities\CompilerOptionParseUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentSet.cs">
<Link>InternalUtilities\ConcurrentSet.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConsList`1.cs">
<Link>InternalUtilities\ConsList`1.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DecimalUtilities.cs">
<Link>InternalUtilities\DecimalUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DocumentationCommentXmlNames.cs">
<Link>InternalUtilities\DocumentationCommentXmlNames.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EncodingExtensions.cs">
<Link>InternalUtilities\EncodingExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumUtilties.cs">
<Link>InternalUtilities\EnumUtilties.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FailFast.cs">
<Link>InternalUtilities\FailFast.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FatalError.cs">
<Link>InternalUtilities\FatalError.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FileNameUtilities.cs">
<Link>InternalUtilities\FileNameUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ImmutableListExtensions.cs">
<Link>InternalUtilities\ImmutableListExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Index.cs">
<Link>InternalUtilities\Index.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ISetExtensions.cs">
<Link>InternalUtilities\ISetExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\MultiDictionary.cs">
<Link>InternalUtilities\MultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OrderedMultiDictionary.cs">
<Link>InternalUtilities\OrderedMultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SetWithInsertionOrder.cs">
<Link>InternalUtilities\SetWithInsertionOrder.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathKind.cs">
<Link>FileSystem\PathKind.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OneOrMany.cs">
<Link>InternalUtilities\OneOrMany.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PerformanceSensitiveAttribute.cs" Condition="'$(DotNetBuildFromSource)' == 'true'">
<Link>InternalUtilities\PerformanceSensitiveAttribute.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PlatformInformation.cs">
<Link>InternalUtilities\PlatformInformation.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Range.cs">
<Link>InternalUtilities\Range.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReaderWriterLockSlimExtensions.cs">
<Link>InternalUtilities\ReaderWriterLockSlimExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SemaphoreSlimExtensions.cs">
<Link>InternalUtilities\SemaphoreSlimExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StackGuard.cs">
<Link>InternalUtilities\StackGuard.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StreamExtensions.cs">
<Link>InternalUtilities\StreamExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringTable.cs" Link="InternalUtilities\StringTable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\TextChangeRangeExtensions.cs">
<Link>InternalUtilities\TextChangeRangeExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\WeakReferenceExtensions.cs">
<Link>InternalUtilities\WeakReferenceExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\FileUtilities.cs">
<Link>FileSystem\FileUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathUtilities.cs">
<Link>FileSystem\PathUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReflectionUtilities.cs">
<Link>InternalUtilities\ReflectionUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs">
<Link>InternalUtilities\UnicodeCharacterUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)CodeActions\CodeActionRequestPriority.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AccessibilityModifiersRequired.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AddImportPlacement.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOption2`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOptions2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\EditorConfigSeverityStrings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ExpressionBodyPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NamespaceDeclarationPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NotificationOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\OperatorPlacementWhenWrappingPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ParenthesesPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArray`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IPragmaSuppressionsAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedDiagnostic.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNode.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNodeOrToken.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxToken.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\AbstractVirtualCharService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\IVirtualCharService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualChar.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Chunks.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Enumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticAnalyzerExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticDescriptorExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectWriterExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\FeatureFlagStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\IPrecedenceService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\PrecedenceKind.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedParametersPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedValuePreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\NormalizedTextSpanCollection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree`2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TextSpanIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Editing\GenerationOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AnalyzerConfigOptionsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ChildSyntaxListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticSeverityExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\NotificationOptionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.TypeSwitch.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ReportDiagnosticExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ImmutableArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\LinkedListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\LocationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ParenthesizedExpressionSyntaxExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Fading\FadingOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\CustomDataFlowAnalysis.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\DataFlowAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\FlowCaptureKind.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\LValueFlowCaptureProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.AnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.BasicBlockAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.FlowGraphAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.OperationTreeAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.Walker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\AbstractSyntaxFormattingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\BottomUpBaseIndentationFinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\ContextIntervalTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.AnchorData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.IndentationData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.InitialContextFinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressSpacingData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressWrappingData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractAggregatedFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.OperationApplier.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.AbstractComplexTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.FormattedWhitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.ModifiedWhitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.Whitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\ChainedFormattingRules.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\NodeOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenPairWithOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Changes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Iterator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Debug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.NodeAndText.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.StructuredTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaDataWithList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingDiagnosticIds.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions.IndentStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\IFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\ISyntaxFormattingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\AbstractFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\BaseIndentationFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\CompatAbstractFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAlignTokensOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAnchorIndentationOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustNewLinesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustSpacesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextIndentBlockOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextSuppressOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NoOpFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AnchorIndentationOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\FormattingOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\StringBuilderPool.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\AbstractTriviaFormatter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumn.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnDelta.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\IUnnecessaryImportsProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\AbstractUnnecessaryImportsProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\EmptyLogBlock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\FunctionId.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\FunctionIdOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\ILogger.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\Logger.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\LogLevel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\Logger.LogBlock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\LogMessage.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Capitalization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_SymbolSpec.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleRules.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\AccessibilityExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\MutableNamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\NamingStylePreferences.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SerializableNamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SymbolSpecification.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDictionary.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\NamingStylePreferenceEditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\IOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\IOptionWithGroup.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\LocalUserProfileStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionGroup.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionDefinition.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionKey2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionStorageLocation2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\Option2`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\PerLanguageOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\RoamingProfileStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SelectedMembers\AbstractSelectedMembers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ForEachSymbols.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractDocumentationCommentService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractSyntaxFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ExternalSourceInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IDocumentationCommentService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ISemanticFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IFileBanner.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFactsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxKinds.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\AliasAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAddImportsAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAllowVarAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\SpecialTypeAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\SymbolAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\Rune.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeDebug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeUtility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\Utf16Utility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)TestHooks\IExpeditableDelaySource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AbstractSpeculationAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AliasSymbolCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AnnotationTable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AsyncLazy`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BidirectionalMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Builder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Edge.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Serialization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CommonFormattingHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ComparerWithState.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Contract.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PathMetadataUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PublicContract.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EditDistance.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EditorConfigFileGenerator_NamingStyles.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EventMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IBidirectionalMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ICacheEntry.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ICollectionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IGroupingExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IntegerUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReferenceCountedDisposable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\LazyInitialization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.ChoiceMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.RepeatMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SequenceMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SingleMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\NonReentrantLock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PooledBuilderExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedOperator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedType.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\PredefinedTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SemanticModelExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SimpleIntervalTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SourceTextExtensions_SharedWithCodeStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SpecialTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolDisplayPartExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeOrTokenExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TextLineExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TextSpanExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\CompilerPathUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMapExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ConcatImmutableArray`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposableCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\RestrictedInternalsVisibleToAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SemaphoreSlimFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SerializableBytes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SoftCrashException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SpecializedTasks.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringBreaker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\WordSimilarityChecker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringEscapeEncoder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringSlice.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SyntaxPath.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskFactoryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TopologicalSorter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ConstantValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedRecoverableValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeakValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\WeakEventHandler.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AccessibilityUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\BasicBlockExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowGraphExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowRegionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IAssemblySymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ICollectionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ICompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\INamedTypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\INamespaceOrTypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IParameterSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.RequiresUnsafeModifierVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions_Accessibility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\MethodKindExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\OperationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StackExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolInfoExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TypeOrNamespaceUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ValueUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\ArrayBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\Extensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\IPooled.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDisposer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledHashSet.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledObject.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledStringBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\SharedPools.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolDisplayFormats.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolVisibility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.AssemblyComparers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.EquivalenceVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.GetHashCodeVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticAnalyzerCategory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticCategory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IBuiltInAnalyzer.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" GenerateSource="true" Link="CompilerExtensionsResources.resx" />
<None Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" />
</ItemGroup>
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
<ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" />
</ItemGroup>
<ItemGroup>
<Folder Include="$(MSBuildThisFileDirectory)Extensions\Compiler\" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>ec946164-1e17-410b-b7d9-7de7e6268d63</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>Microsoft.CodeAnalysis.Shared</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentDictionaryExtensions.cs" Link="InternalUtilities\ConcurrentDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConfiguredYieldAwaitable.cs" Link="InternalUtilities\ConfiguredYieldAwaitable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Debug.cs" Link="InternalUtilities\Debug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumerableExtensions.cs" Link="InternalUtilities\EnumerableExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs" Link="InternalUtilities\ExceptionUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\IReadOnlySet.cs" Link="InternalUtilities\IReadOnlySet.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\KeyValuePairUtil.cs" Link="InternalUtilities\KeyValuePairUtil.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonCopyableAttribute.cs" Link="InternalUtilities\NonCopyableAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NonDefaultableAttribute.cs" Link="InternalUtilities\NonDefaultableAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs" Link="InternalUtilities\NullableAttributes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReferenceEqualityComparer.cs" Link="InternalUtilities\ReferenceEqualityComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs" Link="InternalUtilities\RoslynString.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.cs" Link="InternalUtilities\SpecializedCollections.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SharedStopwatch.cs" Link="InternalUtilities\SharedStopwatch.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Collection.cs" Link="InternalUtilities\SpecializedCollections.Empty.Collection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.cs" Link="InternalUtilities\SpecializedCollections.Empty.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" Link="InternalUtilities\SpecializedCollections.Empty.Dictionary.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Empty.Enumerator`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.List.cs" Link="InternalUtilities\SpecializedCollections.Empty.List.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Empty.Set.cs" Link="InternalUtilities\SpecializedCollections.Empty.Set.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Collection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Enumerable`2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" Link="InternalUtilities\SpecializedCollections.ReadOnly.Set.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Collection`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" Link="InternalUtilities\SpecializedCollections.Singleton.Enumerator`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringExtensions.cs" Link="InternalUtilities\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ValueTaskFactory.cs" Link="InternalUtilities\ValueTaskFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\VoidResult.cs" Link="InternalUtilities\VoidResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\YieldAwaitableExtensions.cs" Link="InternalUtilities\YieldAwaitableExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs" Link="Syntax\SyntaxTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ImmutableArrayExtensions.cs" Link="Collections\ImmutableArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\BitVector.cs" Link="Collections\BitVector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs" Link="InternalUtilities\Hash.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\GeneratedCodeUtilities.cs" Link="InternalUtilities\GeneratedCodeUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\IObjectWritable.cs" Link="Serialization\IObjectWritable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinder.cs" Link="Serialization\ObjectBinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectBinderSnapshot.cs" Link="Serialization\ObjectBinderSnapshot.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectReader.cs" Link="Serialization\ObjectReader.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\ObjectWriter.cs" Link="Serialization\ObjectWriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Serialization\SerializationThreadPool.cs" Link="Serialization\SerializationThreadPool.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SourceCodeKindExtensions.cs" Link="Utilities\Compiler\SourceCodeKindExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\SpecialTypeExtensions.cs" Link="Extensions\Compiler\SpecialTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\ArrayBuilderExtensions.cs">
<Link>Collections\ArrayBuilderExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\DictionaryExtensions.cs">
<Link>Collections\DictionaryExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\Boxes.cs">
<Link>Collections\Boxes.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\Collections\OrderPreservingMultiDictionary.cs">
<Link>Collections\OrderPreservingMultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\EncodedStringText.cs">
<Link>EncodedStringText.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\RelativePathResolver.cs">
<Link>FileSystem\RelativePathResolver.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\AssemblyIdentityUtils.cs">
<Link>InternalUtilities\AssemblyIdentityUtils.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\BitArithmeticUtilities.cs">
<Link>InternalUtilities\BitArithmeticUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ArrayExtensions.cs">
<Link>InternalUtilities\ArrayExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\CompilerOptionParseUtilities.cs">
<Link>InternalUtilities\CompilerOptionParseUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConcurrentSet.cs">
<Link>InternalUtilities\ConcurrentSet.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ConsList`1.cs">
<Link>InternalUtilities\ConsList`1.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DecimalUtilities.cs">
<Link>InternalUtilities\DecimalUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\DocumentationCommentXmlNames.cs">
<Link>InternalUtilities\DocumentationCommentXmlNames.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EncodingExtensions.cs">
<Link>InternalUtilities\EncodingExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\EnumUtilties.cs">
<Link>InternalUtilities\EnumUtilties.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FailFast.cs">
<Link>InternalUtilities\FailFast.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FatalError.cs">
<Link>InternalUtilities\FatalError.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\FileNameUtilities.cs">
<Link>InternalUtilities\FileNameUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ImmutableListExtensions.cs">
<Link>InternalUtilities\ImmutableListExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Index.cs">
<Link>InternalUtilities\Index.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ISetExtensions.cs">
<Link>InternalUtilities\ISetExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\MultiDictionary.cs">
<Link>InternalUtilities\MultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OrderedMultiDictionary.cs">
<Link>InternalUtilities\OrderedMultiDictionary.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SetWithInsertionOrder.cs">
<Link>InternalUtilities\SetWithInsertionOrder.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathKind.cs">
<Link>FileSystem\PathKind.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\OneOrMany.cs">
<Link>InternalUtilities\OneOrMany.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PerformanceSensitiveAttribute.cs" Condition="'$(DotNetBuildFromSource)' == 'true'">
<Link>InternalUtilities\PerformanceSensitiveAttribute.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\PlatformInformation.cs">
<Link>InternalUtilities\PlatformInformation.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\Range.cs">
<Link>InternalUtilities\Range.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReaderWriterLockSlimExtensions.cs">
<Link>InternalUtilities\ReaderWriterLockSlimExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\SemaphoreSlimExtensions.cs">
<Link>InternalUtilities\SemaphoreSlimExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StackGuard.cs">
<Link>InternalUtilities\StackGuard.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StreamExtensions.cs">
<Link>InternalUtilities\StreamExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\StringTable.cs" Link="InternalUtilities\StringTable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\TextChangeRangeExtensions.cs">
<Link>InternalUtilities\TextChangeRangeExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\WeakReferenceExtensions.cs">
<Link>InternalUtilities\WeakReferenceExtensions.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\FileUtilities.cs">
<Link>FileSystem\FileUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\FileSystem\PathUtilities.cs">
<Link>FileSystem\PathUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\ReflectionUtilities.cs">
<Link>InternalUtilities\ReflectionUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs">
<Link>InternalUtilities\UnicodeCharacterUtilities.cs</Link>
</Compile>
<Compile Include="$(MSBuildThisFileDirectory)CodeActions\CodeActionRequestPriority.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AccessibilityModifiersRequired.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\AddImportPlacement.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOption2`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\CodeStyleOptions2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\EditorConfigSeverityStrings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ExpressionBodyPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NamespaceDeclarationPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\NotificationOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\OperatorPlacementWhenWrappingPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\ParenthesesPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TemporaryArray`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IPragmaSuppressionsAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedDiagnostic.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNode.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxNodeOrToken.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxToken.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\Common\EmbeddedSyntaxTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\AbstractVirtualCharService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\IVirtualCharService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualChar.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Chunks.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.cs" />
<Compile Include="$(MSBuildThisFileDirectory)EmbeddedLanguages\VirtualChars\VirtualCharSequence.Enumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticAnalyzerExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticDescriptorExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectWriterExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\FeatureFlagStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\IPrecedenceService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\Precedence\PrecedenceKind.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedParametersPreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)CodeStyle\UnusedValuePreference.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\IntervalTree`1.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\NormalizedTextSpanCollection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\SimpleIntervalTree`2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Collections\TextSpanIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Editing\GenerationOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AnalyzerConfigOptionsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ChildSyntaxListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticSeverityExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\NotificationOptionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ObjectExtensions.TypeSwitch.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ReportDiagnosticExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ImmutableArrayExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\LinkedListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\LocationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ParenthesizedExpressionSyntaxExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Fading\FadingOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\CustomDataFlowAnalysis.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\DataFlowAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\FlowCaptureKind.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\LValueFlowCaptureProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.AnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.BasicBlockAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.DataFlowAnalyzer.FlowGraphAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.OperationTreeAnalysisData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageAnalysis.Walker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FlowAnalysis\SymbolUsageAnalysis\SymbolUsageResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\AbstractSyntaxFormattingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\BottomUpBaseIndentationFinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\ContextIntervalTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.AnchorData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.IndentationData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\FormattingContext.InitialContextFinder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressIntervalIntrospector.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressSpacingData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Context\SuppressWrappingData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractAggregatedFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormatEngine.OperationApplier.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.AbstractComplexTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.FormattedWhitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.ModifiedWhitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\AbstractTriviaDataFactory.Whitespace.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\ChainedFormattingRules.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\NodeOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenPairWithOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Changes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TokenStream.Iterator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Debug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.NodeAndText.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TreeData.StructuredTrivia.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaData.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Engine\TriviaDataWithList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingDiagnosticIds.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions.IndentStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\FormattingOptions2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\IFormattingResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\ISyntaxFormattingService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\AbstractFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\BaseIndentationFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\CompatAbstractFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAlignTokensOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextAnchorIndentationOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustNewLinesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextGetAdjustSpacesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextIndentBlockOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NextSuppressOperationAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\NoOpFormattingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustNewLinesOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AdjustSpacesOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AlignTokensOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\AnchorIndentationOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\FormattingOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\IndentBlockOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOperation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\Rules\Operations\SuppressOption.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\StringBuilderPool.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\AbstractTriviaFormatter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumn.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnDelta.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\LineColumnRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Formatting\TriviaEngine\TriviaList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\IUnnecessaryImportsProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\RemoveUnnecessaryImports\AbstractUnnecessaryImportsProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\EmptyLogBlock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\FunctionId.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\FunctionIdOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\ILogger.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\Logger.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\LogLevel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\Logger.LogBlock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Log\LogMessage.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Capitalization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_NamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\EditorConfig\EditorConfigNamingStyleParser_SymbolSpec.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyle.WordSpanEnumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\NamingStyleRules.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\AccessibilityExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\MutableNamingStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\NamingStylePreferences.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SerializableNamingRule.cs" />
<Compile Include="$(MSBuildThisFileDirectory)NamingStyles\Serialization\SymbolSpecification.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDictionary.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\EditorConfigStorageLocation`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\IEditorConfigStorageLocation2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\EditorConfig\NamingStylePreferenceEditorConfigStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\IOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\IOptionWithGroup.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\LocalUserProfileStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionGroup.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionDefinition.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionKey2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\OptionStorageLocation2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\Option2`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\PerLanguageOption2.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Options\RoamingProfileStorageLocation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SelectedMembers\AbstractSelectedMembers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ForEachSymbols.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractDocumentationCommentService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\AbstractSyntaxFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ExternalSourceInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IDocumentationCommentService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SemanticFacts\ISemanticFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\IFileBanner.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFacts.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxFactsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Services\SyntaxFacts\ISyntaxKinds.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\AliasAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAddImportsAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\DoNotAllowVarAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\SpecialTypeAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Simplification\SymbolAnnotation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\Rune.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeDebug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\UnicodeUtility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System.Text\Utf16Utility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)TestHooks\IExpeditableDelaySource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AbstractSpeculationAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AliasSymbolCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AnnotationTable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\AsyncLazy`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BidirectionalMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Builder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Edge.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Node.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\BKTree.Serialization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CancellableLazy`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CommonFormattingHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ComparerWithState.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Contract.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PathMetadataUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PublicContract.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EditDistance.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EditorConfigFileGenerator_NamingStyles.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EventMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IBidirectionalMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ICacheEntry.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ICollectionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IGroupingExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IntegerUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReadOnlyListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\IReferenceCountedDisposable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\LazyInitialization.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.ChoiceMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.RepeatMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SequenceMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher.SingleMatcher.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\Matcher`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\NonReentrantLock.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PooledBuilderExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedOperator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\PredefinedType.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\PredefinedTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SemanticModelExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SimpleIntervalTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SourceTextExtensions_SharedWithCodeStyle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SpecialTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolDisplayPartExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeOrTokenExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTokenListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTreeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxTriviaListExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TextLineExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TextSpanExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\CompilerPathUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableDictionaryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMap.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\CompilerUtilities\ImmutableHashMapExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ConcatImmutableArray`1.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposableCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\RestrictedInternalsVisibleToAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SemaphoreSlimFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SerializableBytes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SoftCrashException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SpecializedTasks.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringBreaker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\WordSimilarityChecker.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringEscapeEncoder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\StringSlice.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SyntaxPath.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TaskFactoryExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\TopologicalSorter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ConstantValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\ValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedRecoverableValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeaklyCachedValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ValuesSources\WeakValueSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\WeakEventHandler.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AccessibilityUtilities.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\BasicBlockExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowGraphExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ControlFlowRegionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IAssemblySymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ICollectionExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ICompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\INamedTypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\INamespaceOrTypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IParameterSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions.RequiresUnsafeModifierVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ISymbolExtensions_Accessibility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.MinimalAccessibilityVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\MethodKindExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\OperationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\StackExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolInfoExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SymbolUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TypeOrNamespaceUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ValueUsageInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\ArrayBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\Extensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\IPooled.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledDisposer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledHashSet.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledObject.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\PooledStringBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ObjectPools\SharedPools.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolDisplayFormats.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolVisibility.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.AssemblyComparers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.EquivalenceVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.GetHashCodeVisitor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.ParameterSymbolEqualityComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SymbolEquivalenceComparer.SignatureTypeSymbolEquivalenceComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticAnalyzerCategory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticCategory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\IBuiltInAnalyzer.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" GenerateSource="true" Link="CompilerExtensionsResources.resx" />
<None Include="$(MSBuildThisFileDirectory)CompilerExtensionsResources.resx" />
</ItemGroup>
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
<ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" />
</ItemGroup>
<ItemGroup>
<Folder Include="$(MSBuildThisFileDirectory)Extensions\Compiler\" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.ClassData.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class)
Protected Class ClassData
Public Property Name As String
Public Property Position As Object = 0
Public Property Bases As Object
Public Property ImplementedInterfaces As Object
Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class)
Protected Class ClassData
Public Property Name As String
Public Property Position As Object = 0
Public Property Bases As Object
Public Property ImplementedInterfaces As Object
Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/XmlLiteralsTests_UseSiteErrors.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class XmlLiteralTests
Inherits BasicTestBase
<Fact()>
Public Sub XDocumentTypesMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XDocumentTypesMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <?xml version="1.0"?><x/><?p?>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XDeclaration' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XDocument' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XProcessingInstruction' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XCommentTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XCommentTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <!-- comment -->
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XComment' from assembly or module 'XCommentTypeMissing.dll' failed.
Private F As Object = <!-- comment -->
~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XElementTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XElementTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XContainer = <x/>
Private F2 As Object = F1.<x>
Private F3 As Object = F1.@x
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed.
Private F1 As XContainer = <x/>
~
BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed.
Private F3 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XContainer'.
Private F3 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XElementConstructorInaccessible()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XName
End Class
Public Class XElement
Friend Sub New(o As Object)
End Sub
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XName = Nothing
Private F2 As Object = <<%= F1 %>/>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30517: Overload resolution failed because no 'New' is accessible.
Private F2 As Object = <<%= F1 %>/>
~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XAttributeTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XAttributeTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Private F1 As Object = <x <%= Nothing %>/>
Private F2 As Object = <x <%= "a" %>="b"/>
Private F3 As Object = <x a=<%= "b" %>/>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XAttribute' from assembly or module 'XAttributeTypeMissing.dll' failed.
Private F2 As Object = <x <%= "a" %>="b"/>
~~~~~~~~~~~~~~
BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'.
Private F3 As Object = <x a=<%= "b" %>/>
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XAttributeConstructorMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XAttributeTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Private F1 As Object = <x <%= Nothing %>/>
Private F2 As Object = <x <%= "a" %>="b"/>
Private F3 As Object = <x a=<%= "b" %>/>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As List(Of XAttribute), o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30057: Too many arguments to 'Public Sub New(o As Object)'.
Private F2 As Object = <x <%= "a" %>="b"/>
~~~
BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'.
Private F3 As Object = <x a=<%= "b" %>/>
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNameTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XContainer
Public Sub Add(o As Object)
End Sub
End Class
Public Class XElement
Inherits XContainer
Public Sub New(o As Object)
End Sub
End Class
Public Class XAttribute
Public Sub New(x As Object, y As Object)
End Sub
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNameTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F1 As Object = <x/>
Private F2 As Object = <<%= Nothing %> a="b"/>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed.
Private F1 As Object = <x/>
~
BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed.
Private F2 As Object = <<%= Nothing %> a="b"/>
~
]]></errors>)
End Sub
<Fact()>
Public Sub XContainerTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XContainerTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = <x/>
Private F2 As XElement = <x a="b"/>
Private F3 As XElement = <x>c</>
Private F4 As XElement = F1.<x>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F2 As XElement = <x a="b"/>
~~~~~~~~~~
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F3 As XElement = <x>c</>
~~~~~~~
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F4 As XElement = F1.<x>
~~~~~~
BC36807: XML elements cannot be selected from type 'XElement'.
Private F4 As XElement = F1.<x>
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XContainerMemberNotInvocable()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <x>c</>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Add' is not a member of 'XContainer'.
Private F As Object = <x>c</>
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XCDataTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="XCDataTypeMissing">
<file name="c.vb">
Option Strict On
Module M
Private F As Object = <![CDATA[value]]>
End Module
</file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors>
BC31091: Import of type 'XCData' from assembly or module 'XCDataTypeMissing.dll' failed.
Private F As Object = <![CDATA[value]]>
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub XNamespaceTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceTypeMissing">
<file name="c.vb"><![CDATA[
Class C
Private F = GetXmlNamespace()
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing.dll' failed.
Private F = GetXmlNamespace()
~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNamespaceTypeMissing_2()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceTypeMissing_2">
<file name="c.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/">
Class C
Private F = <x><%= Nothing %></>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'InternalXmlHelper' from assembly or module 'XNamespaceTypeMissing_2.dll' failed.
Private F = <x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing_2.dll' failed.
Private F = <x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNamespaceGetMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceGetMissing">
<file name="c.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/">
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Shared F As Object = <p:x><%= Nothing %></>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function CreateNamespaceAttribute(name As XName, ns As XNamespace) As XAttribute
Return Nothing
End Function
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Get' is not a member of 'XNamespace'.
Shared F As Object = <p:x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ExtensionTypesMissing()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="ExtensionTypesMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = <x/>
Private F2 As Object = F1.<x>
Private F3 As Object = F1.<x>.<y>
Private F4 As Object = F1.@x
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'Extensions' from assembly or module 'ExtensionTypesMissing.dll' failed.
Private F3 As Object = F1.<x>.<y>
~~~~~~~~~~
BC36807: XML elements cannot be selected from type 'IEnumerable(Of XContainer)'.
Private F3 As Object = F1.<x>.<y>
~~~~~~~~~~
BC31091: Import of type 'InternalXmlHelper' from assembly or module 'ExtensionTypesMissing.dll' failed.
Private F4 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XElement'.
Private F4 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ExtensionMethodAndPropertyMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Module Extensions
End Module
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = Nothing
Private F2 As Object = F1.<x>
Private F3 As Object = F1.@x
End Class
Namespace My
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Elements' is not a member of 'XContainer'.
Private F2 As Object = F1.<x>
~~~~~~
BC36807: XML elements cannot be selected from type 'XElement'.
Private F2 As Object = F1.<x>
~~~~~~
BC30456: 'AttributeValue' is not a member of 'InternalXmlHelper'.
Private F3 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XElement'.
Private F3 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ValueExtensionPropertyMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XElement
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Function F(x As IEnumerable(Of XElement)) As String
Return x.Value
End Function
End Class
Namespace My
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.
Return x.Value
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ValueExtensionPropertyUnexpectedSignature()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Xml.Linq
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XElement
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Function F(x As IEnumerable(Of XElement)) As String
Return x.VALUE
End Function
End Class
Namespace My
Public Module InternalXmlHelper
Public ReadOnly Property Value(x As IEnumerable(Of XElement), y As Object, z As Object) As Object
Get
Return Nothing
End Get
End Property
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.
Return x.VALUE
~~~~~~~
]]></errors>)
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class XmlLiteralTests
Inherits BasicTestBase
<Fact()>
Public Sub XDocumentTypesMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XDocumentTypesMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <?xml version="1.0"?><x/><?p?>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XDeclaration' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XDocument' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XProcessingInstruction' from assembly or module 'XDocumentTypesMissing.dll' failed.
Private F As Object = <?xml version="1.0"?><x/><?p?>
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XCommentTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XCommentTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <!-- comment -->
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XComment' from assembly or module 'XCommentTypeMissing.dll' failed.
Private F As Object = <!-- comment -->
~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XElementTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XElementTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XContainer = <x/>
Private F2 As Object = F1.<x>
Private F3 As Object = F1.@x
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed.
Private F1 As XContainer = <x/>
~
BC31091: Import of type 'XElement' from assembly or module 'XElementTypeMissing.dll' failed.
Private F3 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XContainer'.
Private F3 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XElementConstructorInaccessible()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XName
End Class
Public Class XElement
Friend Sub New(o As Object)
End Sub
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XName = Nothing
Private F2 As Object = <<%= F1 %>/>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30517: Overload resolution failed because no 'New' is accessible.
Private F2 As Object = <<%= F1 %>/>
~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XAttributeTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XAttributeTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Private F1 As Object = <x <%= Nothing %>/>
Private F2 As Object = <x <%= "a" %>="b"/>
Private F3 As Object = <x a=<%= "b" %>/>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XAttribute' from assembly or module 'XAttributeTypeMissing.dll' failed.
Private F2 As Object = <x <%= "a" %>="b"/>
~~~~~~~~~~~~~~
BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'.
Private F3 As Object = <x a=<%= "b" %>/>
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XAttributeConstructorMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XAttributeTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Private F1 As Object = <x <%= Nothing %>/>
Private F2 As Object = <x <%= "a" %>="b"/>
Private F3 As Object = <x a=<%= "b" %>/>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As List(Of XAttribute), o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30057: Too many arguments to 'Public Sub New(o As Object)'.
Private F2 As Object = <x <%= "a" %>="b"/>
~~~
BC30456: 'CreateAttribute' is not a member of 'InternalXmlHelper'.
Private F3 As Object = <x a=<%= "b" %>/>
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNameTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XContainer
Public Sub Add(o As Object)
End Sub
End Class
Public Class XElement
Inherits XContainer
Public Sub New(o As Object)
End Sub
End Class
Public Class XAttribute
Public Sub New(x As Object, y As Object)
End Sub
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNameTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F1 As Object = <x/>
Private F2 As Object = <<%= Nothing %> a="b"/>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed.
Private F1 As Object = <x/>
~
BC31091: Import of type 'XName' from assembly or module 'XNameTypeMissing.dll' failed.
Private F2 As Object = <<%= Nothing %> a="b"/>
~
]]></errors>)
End Sub
<Fact()>
Public Sub XContainerTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XContainerTypeMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = <x/>
Private F2 As XElement = <x a="b"/>
Private F3 As XElement = <x>c</>
Private F4 As XElement = F1.<x>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F2 As XElement = <x a="b"/>
~~~~~~~~~~
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F3 As XElement = <x>c</>
~~~~~~~
BC31091: Import of type 'XContainer' from assembly or module 'XContainerTypeMissing.dll' failed.
Private F4 As XElement = F1.<x>
~~~~~~
BC36807: XML elements cannot be selected from type 'XElement'.
Private F4 As XElement = F1.<x>
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XContainerMemberNotInvocable()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Private F As Object = <x>c</>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Add' is not a member of 'XContainer'.
Private F As Object = <x>c</>
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XCDataTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="XCDataTypeMissing">
<file name="c.vb">
Option Strict On
Module M
Private F As Object = <![CDATA[value]]>
End Module
</file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors>
BC31091: Import of type 'XCData' from assembly or module 'XCDataTypeMissing.dll' failed.
Private F As Object = <![CDATA[value]]>
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub XNamespaceTypeMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Namespace System.Xml.Linq
Public Class XObject
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceTypeMissing">
<file name="c.vb"><![CDATA[
Class C
Private F = GetXmlNamespace()
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing.dll' failed.
Private F = GetXmlNamespace()
~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNamespaceTypeMissing_2()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceTypeMissing_2">
<file name="c.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/">
Class C
Private F = <x><%= Nothing %></>
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'InternalXmlHelper' from assembly or module 'XNamespaceTypeMissing_2.dll' failed.
Private F = <x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'XNamespace' from assembly or module 'XNamespaceTypeMissing_2.dll' failed.
Private F = <x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub XNamespaceGetMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Class XNamespace
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="XNamespaceGetMissing">
<file name="c.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/">
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Shared F As Object = <p:x><%= Nothing %></>
End Class
Namespace My
Public Module InternalXmlHelper
Public Function CreateNamespaceAttribute(name As XName, ns As XNamespace) As XAttribute
Return Nothing
End Function
Public Function RemoveNamespaceAttributes(prefixes As String(), namespaces As XNamespace(), attributes As Object, o As Object) As Object
Return Nothing
End Function
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Get' is not a member of 'XNamespace'.
Shared F As Object = <p:x><%= Nothing %></>
~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ExtensionTypesMissing()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation name="ExtensionTypesMissing">
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = <x/>
Private F2 As Object = F1.<x>
Private F3 As Object = F1.<x>.<y>
Private F4 As Object = F1.@x
End Class
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31091: Import of type 'Extensions' from assembly or module 'ExtensionTypesMissing.dll' failed.
Private F3 As Object = F1.<x>.<y>
~~~~~~~~~~
BC36807: XML elements cannot be selected from type 'IEnumerable(Of XContainer)'.
Private F3 As Object = F1.<x>.<y>
~~~~~~~~~~
BC31091: Import of type 'InternalXmlHelper' from assembly or module 'ExtensionTypesMissing.dll' failed.
Private F4 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XElement'.
Private F4 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ExtensionMethodAndPropertyMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">< As XName
Return Nothing
End Function
End Class
Public Module Extensions
End Module
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Xml.Linq
Class C
Private F1 As XElement = Nothing
Private F2 As Object = F1.<x>
Private F3 As Object = F1.@x
End Class
Namespace My
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Elements' is not a member of 'XContainer'.
Private F2 As Object = F1.<x>
~~~~~~
BC36807: XML elements cannot be selected from type 'XElement'.
Private F2 As Object = F1.<x>
~~~~~~
BC30456: 'AttributeValue' is not a member of 'InternalXmlHelper'.
Private F3 As Object = F1.@x
~~~~~
BC36808: XML attributes cannot be selected from type 'XElement'.
Private F3 As Object = F1.@x
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ValueExtensionPropertyMissing()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XElement
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Function F(x As IEnumerable(Of XElement)) As String
Return x.Value
End Function
End Class
Namespace My
Public Module InternalXmlHelper
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.
Return x.Value
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ValueExtensionPropertyUnexpectedSignature()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Xml.Linq
Namespace System.Xml.Linq
Public Class XObject
End Class
Public Class XElement
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class StandardModuleAttribute : Inherits System.Attribute
End Class
End Namespace
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Imports System.Xml.Linq
Class C
Function F(x As IEnumerable(Of XElement)) As String
Return x.VALUE
End Function
End Class
Namespace My
Public Module InternalXmlHelper
Public ReadOnly Property Value(x As IEnumerable(Of XElement), y As Object, z As Object) As Object
Get
Return Nothing
End Get
End Property
End Module
End Namespace
]]></file>
</compilation>, references:={New VisualBasicCompilationReference(compilation1)})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC31190: XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.
Return x.VALUE
~~~~~~~
]]></errors>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Tools/AnalyzerRunner/app.config | <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcServer enabled="true" />
<appDomainManagerType value="Microsoft.SourceBrowser.Common.CustomAppDomainManager"/>
<appDomainManagerAssembly value="Microsoft.SourceBrowser.Common"/>
</runtime>
</configuration>
| <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcServer enabled="true" />
<appDomainManagerType value="Microsoft.SourceBrowser.Common.CustomAppDomainManager"/>
<appDomainManagerAssembly value="Microsoft.SourceBrowser.Common"/>
</runtime>
</configuration>
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/CodeStyle/Core/Analyzers/AnalyzerConfigOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis
{
internal sealed class CompilerAnalyzerConfigOptions : AnalyzerConfigOptions
{
public static CompilerAnalyzerConfigOptions Empty { get; } = new CompilerAnalyzerConfigOptions();
private CompilerAnalyzerConfigOptions()
{
}
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
{
value = null;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis
{
internal sealed class CompilerAnalyzerConfigOptions : AnalyzerConfigOptions
{
public static CompilerAnalyzerConfigOptions Empty { get; } = new CompilerAnalyzerConfigOptions();
private CompilerAnalyzerConfigOptions()
{
}
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
{
value = null;
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
[ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared]
[ProvidesMethod(Methods.TextDocumentCompletionName)]
internal class CompletionHandler : AbstractStatelessRequestHandler<CompletionParams, CompletionList?>
{
public override string Method => Methods.TextDocumentCompletionName;
private const string CreateEventHandlerCommandTitle = "Create Event Handler";
private static readonly Command s_retriggerCompletionCommand = new Command()
{
CommandIdentifier = StringConstants.RetriggerCompletionCommand,
Title = "Re-trigger completions"
};
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CompletionHandler()
{
}
public override TextDocumentIdentifier GetTextDocumentIdentifier(CompletionParams request) => request.TextDocument;
public override async Task<CompletionList?> HandleRequestAsync(CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
if (request.Context is VSInternalCompletionContext completionContext && completionContext.InvokeKind == VSInternalCompletionInvokeKind.Deletion)
{
// Don't trigger completions on backspace.
return null;
}
var document = context.Document;
if (document == null)
{
return null;
}
var completionService = document.Project.LanguageServices.GetRequiredService<IXamlCompletionService>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position));
var completionResult = await completionService.GetCompletionsAsync(new XamlCompletionContext(document, offset, request.Context?.TriggerCharacter?.FirstOrDefault() ?? '\0'), cancellationToken: cancellationToken).ConfigureAwait(false);
if (completionResult?.Completions == null)
{
return null;
}
var commitCharactersCache = new Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>>();
return new VSInternalCompletionList
{
Items = completionResult.Completions.Select(c => CreateCompletionItem(c, document.Id, text, request.Position, request.TextDocument, commitCharactersCache)).ToArray(),
SuggestionMode = false,
};
}
private static CompletionItem CreateCompletionItem(XamlCompletionItem xamlCompletion, DocumentId documentId, SourceText text, Position position, TextDocumentIdentifier textDocument, Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>> commitCharactersCach)
{
var item = new VSInternalCompletionItem
{
Label = xamlCompletion.DisplayText,
VsCommitCharacters = GetCommitCharacters(xamlCompletion, commitCharactersCach),
Detail = xamlCompletion.Detail,
InsertText = xamlCompletion.InsertText,
Preselect = xamlCompletion.Preselect.GetValueOrDefault(),
SortText = xamlCompletion.SortText,
FilterText = xamlCompletion.FilterText,
Kind = GetItemKind(xamlCompletion.Kind),
Description = xamlCompletion.Description,
Icon = xamlCompletion.Icon,
InsertTextFormat = xamlCompletion.IsSnippet ? InsertTextFormat.Snippet : InsertTextFormat.Plaintext,
Data = new CompletionResolveData { ProjectGuid = documentId.ProjectId.Id, DocumentGuid = documentId.Id, Position = position, DisplayText = xamlCompletion.DisplayText }
};
if (xamlCompletion.Span.HasValue)
{
item.TextEdit = new TextEdit
{
NewText = xamlCompletion.InsertText,
Range = ProtocolConversions.LinePositionToRange(text.Lines.GetLinePositionSpan(xamlCompletion.Span.Value))
};
}
if (xamlCompletion.EventDescription.HasValue)
{
item.Command = new Command()
{
CommandIdentifier = StringConstants.CreateEventHandlerCommand,
Arguments = new object[] { textDocument, xamlCompletion.EventDescription },
Title = CreateEventHandlerCommandTitle
};
}
else if (xamlCompletion.RetriggerCompletion)
{
// Retriger completion after commit
item.Command = s_retriggerCompletionCommand;
}
return item;
}
private static SumType<string[], VSInternalCommitCharacter[]> GetCommitCharacters(XamlCompletionItem completionItem, Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>> commitCharactersCache)
{
if (!completionItem.XamlCommitCharacters.HasValue)
{
return completionItem.CommitCharacters;
}
if (commitCharactersCache.TryGetValue(completionItem.Kind, out var cachedCharacters))
{
// If we have already cached the commit characters, return the cached ones
return cachedCharacters.ToArray();
}
var xamlCommitCharacters = completionItem.XamlCommitCharacters.Value;
var commitCharacters = xamlCommitCharacters.Characters.Select(c => new VSInternalCommitCharacter { Character = c.ToString(), Insert = !xamlCommitCharacters.NonInsertCharacters.Contains(c) }).ToImmutableArray();
commitCharactersCache.Add(completionItem.Kind, commitCharacters);
return commitCharacters.ToArray();
}
private static CompletionItemKind GetItemKind(XamlCompletionKind kind)
{
switch (kind)
{
case XamlCompletionKind.Element:
case XamlCompletionKind.ElementName:
return CompletionItemKind.Element;
case XamlCompletionKind.EndTag:
return CompletionItemKind.CloseElement;
case XamlCompletionKind.Attribute:
case XamlCompletionKind.AttachedPropertyValue:
case XamlCompletionKind.ConditionalArgument:
case XamlCompletionKind.DataBoundProperty:
case XamlCompletionKind.MarkupExtensionParameter:
case XamlCompletionKind.PropertyElement:
return CompletionItemKind.Property;
case XamlCompletionKind.ConditionValue:
case XamlCompletionKind.MarkupExtensionValue:
case XamlCompletionKind.PropertyValue:
case XamlCompletionKind.Value:
return CompletionItemKind.Value;
case XamlCompletionKind.Event:
case XamlCompletionKind.EventHandlerDescription:
return CompletionItemKind.Event;
case XamlCompletionKind.NamespaceValue:
case XamlCompletionKind.Prefix:
return CompletionItemKind.Namespace;
case XamlCompletionKind.AttachedPropertyTypePrefix:
case XamlCompletionKind.MarkupExtensionClass:
case XamlCompletionKind.Type:
case XamlCompletionKind.TypePrefix:
return CompletionItemKind.Class;
case XamlCompletionKind.LocalResource:
return CompletionItemKind.LocalResource;
case XamlCompletionKind.SystemResource:
return CompletionItemKind.SystemResource;
case XamlCompletionKind.CData:
case XamlCompletionKind.Comment:
case XamlCompletionKind.ProcessingInstruction:
case XamlCompletionKind.RegionStart:
case XamlCompletionKind.RegionEnd:
return CompletionItemKind.Keyword;
case XamlCompletionKind.Snippet:
return CompletionItemKind.Snippet;
default:
Debug.Fail($"Unhandled {nameof(XamlCompletionKind)}: {Enum.GetName(typeof(XamlCompletionKind), kind)}");
return CompletionItemKind.Text;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
[ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared]
[ProvidesMethod(Methods.TextDocumentCompletionName)]
internal class CompletionHandler : AbstractStatelessRequestHandler<CompletionParams, CompletionList?>
{
public override string Method => Methods.TextDocumentCompletionName;
private const string CreateEventHandlerCommandTitle = "Create Event Handler";
private static readonly Command s_retriggerCompletionCommand = new Command()
{
CommandIdentifier = StringConstants.RetriggerCompletionCommand,
Title = "Re-trigger completions"
};
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CompletionHandler()
{
}
public override TextDocumentIdentifier GetTextDocumentIdentifier(CompletionParams request) => request.TextDocument;
public override async Task<CompletionList?> HandleRequestAsync(CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
if (request.Context is VSInternalCompletionContext completionContext && completionContext.InvokeKind == VSInternalCompletionInvokeKind.Deletion)
{
// Don't trigger completions on backspace.
return null;
}
var document = context.Document;
if (document == null)
{
return null;
}
var completionService = document.Project.LanguageServices.GetRequiredService<IXamlCompletionService>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position));
var completionResult = await completionService.GetCompletionsAsync(new XamlCompletionContext(document, offset, request.Context?.TriggerCharacter?.FirstOrDefault() ?? '\0'), cancellationToken: cancellationToken).ConfigureAwait(false);
if (completionResult?.Completions == null)
{
return null;
}
var commitCharactersCache = new Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>>();
return new VSInternalCompletionList
{
Items = completionResult.Completions.Select(c => CreateCompletionItem(c, document.Id, text, request.Position, request.TextDocument, commitCharactersCache)).ToArray(),
SuggestionMode = false,
};
}
private static CompletionItem CreateCompletionItem(XamlCompletionItem xamlCompletion, DocumentId documentId, SourceText text, Position position, TextDocumentIdentifier textDocument, Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>> commitCharactersCach)
{
var item = new VSInternalCompletionItem
{
Label = xamlCompletion.DisplayText,
VsCommitCharacters = GetCommitCharacters(xamlCompletion, commitCharactersCach),
Detail = xamlCompletion.Detail,
InsertText = xamlCompletion.InsertText,
Preselect = xamlCompletion.Preselect.GetValueOrDefault(),
SortText = xamlCompletion.SortText,
FilterText = xamlCompletion.FilterText,
Kind = GetItemKind(xamlCompletion.Kind),
Description = xamlCompletion.Description,
Icon = xamlCompletion.Icon,
InsertTextFormat = xamlCompletion.IsSnippet ? InsertTextFormat.Snippet : InsertTextFormat.Plaintext,
Data = new CompletionResolveData { ProjectGuid = documentId.ProjectId.Id, DocumentGuid = documentId.Id, Position = position, DisplayText = xamlCompletion.DisplayText }
};
if (xamlCompletion.Span.HasValue)
{
item.TextEdit = new TextEdit
{
NewText = xamlCompletion.InsertText,
Range = ProtocolConversions.LinePositionToRange(text.Lines.GetLinePositionSpan(xamlCompletion.Span.Value))
};
}
if (xamlCompletion.EventDescription.HasValue)
{
item.Command = new Command()
{
CommandIdentifier = StringConstants.CreateEventHandlerCommand,
Arguments = new object[] { textDocument, xamlCompletion.EventDescription },
Title = CreateEventHandlerCommandTitle
};
}
else if (xamlCompletion.RetriggerCompletion)
{
// Retriger completion after commit
item.Command = s_retriggerCompletionCommand;
}
return item;
}
private static SumType<string[], VSInternalCommitCharacter[]> GetCommitCharacters(XamlCompletionItem completionItem, Dictionary<XamlCompletionKind, ImmutableArray<VSInternalCommitCharacter>> commitCharactersCache)
{
if (!completionItem.XamlCommitCharacters.HasValue)
{
return completionItem.CommitCharacters;
}
if (commitCharactersCache.TryGetValue(completionItem.Kind, out var cachedCharacters))
{
// If we have already cached the commit characters, return the cached ones
return cachedCharacters.ToArray();
}
var xamlCommitCharacters = completionItem.XamlCommitCharacters.Value;
var commitCharacters = xamlCommitCharacters.Characters.Select(c => new VSInternalCommitCharacter { Character = c.ToString(), Insert = !xamlCommitCharacters.NonInsertCharacters.Contains(c) }).ToImmutableArray();
commitCharactersCache.Add(completionItem.Kind, commitCharacters);
return commitCharacters.ToArray();
}
private static CompletionItemKind GetItemKind(XamlCompletionKind kind)
{
switch (kind)
{
case XamlCompletionKind.Element:
case XamlCompletionKind.ElementName:
return CompletionItemKind.Element;
case XamlCompletionKind.EndTag:
return CompletionItemKind.CloseElement;
case XamlCompletionKind.Attribute:
case XamlCompletionKind.AttachedPropertyValue:
case XamlCompletionKind.ConditionalArgument:
case XamlCompletionKind.DataBoundProperty:
case XamlCompletionKind.MarkupExtensionParameter:
case XamlCompletionKind.PropertyElement:
return CompletionItemKind.Property;
case XamlCompletionKind.ConditionValue:
case XamlCompletionKind.MarkupExtensionValue:
case XamlCompletionKind.PropertyValue:
case XamlCompletionKind.Value:
return CompletionItemKind.Value;
case XamlCompletionKind.Event:
case XamlCompletionKind.EventHandlerDescription:
return CompletionItemKind.Event;
case XamlCompletionKind.NamespaceValue:
case XamlCompletionKind.Prefix:
return CompletionItemKind.Namespace;
case XamlCompletionKind.AttachedPropertyTypePrefix:
case XamlCompletionKind.MarkupExtensionClass:
case XamlCompletionKind.Type:
case XamlCompletionKind.TypePrefix:
return CompletionItemKind.Class;
case XamlCompletionKind.LocalResource:
return CompletionItemKind.LocalResource;
case XamlCompletionKind.SystemResource:
return CompletionItemKind.SystemResource;
case XamlCompletionKind.CData:
case XamlCompletionKind.Comment:
case XamlCompletionKind.ProcessingInstruction:
case XamlCompletionKind.RegionStart:
case XamlCompletionKind.RegionEnd:
return CompletionItemKind.Keyword;
case XamlCompletionKind.Snippet:
return CompletionItemKind.Snippet;
default:
Debug.Fail($"Unhandled {nameof(XamlCompletionKind)}: {Enum.GetName(typeof(XamlCompletionKind), kind)}");
return CompletionItemKind.Text;
}
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/Core/Portable/GenerateMember/AbstractGenerateMemberService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GenerateMember
{
internal abstract partial class AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
{
protected AbstractGenerateMemberService()
{
}
protected static readonly ISet<TypeKind> EnumType = new HashSet<TypeKind> { TypeKind.Enum };
protected static readonly ISet<TypeKind> ClassInterfaceModuleStructTypes = new HashSet<TypeKind>
{
TypeKind.Class,
TypeKind.Module,
TypeKind.Struct,
TypeKind.Interface
};
protected static bool ValidateTypeToGenerateIn(
INamedTypeSymbol typeToGenerateIn,
bool isStatic,
ISet<TypeKind> typeKinds)
{
if (typeToGenerateIn == null)
{
return false;
}
if (typeToGenerateIn.IsAnonymousType)
{
return false;
}
if (!typeKinds.Contains(typeToGenerateIn.TypeKind))
{
return false;
}
if (typeToGenerateIn.TypeKind == TypeKind.Interface && isStatic)
{
return false;
}
// TODO(cyrusn): Make sure that there is a totally visible part somewhere (i.e.
// venus) that we can generate into.
var locations = typeToGenerateIn.Locations;
return locations.Any(loc => loc.IsInSource);
}
protected static bool TryDetermineTypeToGenerateIn(
SemanticDocument document,
INamedTypeSymbol containingType,
TExpressionSyntax simpleNameOrMemberAccessExpression,
CancellationToken cancellationToken,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic)
{
TryDetermineTypeToGenerateInWorker(
document, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out typeToGenerateIn, out isStatic);
if (typeToGenerateIn != null)
{
typeToGenerateIn = typeToGenerateIn.OriginalDefinition;
}
return typeToGenerateIn != null;
}
private static void TryDetermineTypeToGenerateInWorker(
SemanticDocument semanticDocument,
INamedTypeSymbol containingType,
TExpressionSyntax expression,
CancellationToken cancellationToken,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic)
{
typeToGenerateIn = null;
isStatic = false;
var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = semanticDocument.SemanticModel;
if (syntaxFacts.IsSimpleMemberAccessExpression(expression))
{
// Figure out what's before the dot. For VB, that also means finding out
// what ".X" might mean, even when there's nothing before the dot itself.
var beforeDotExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(
expression, allowImplicitTarget: true);
if (beforeDotExpression != null)
{
DetermineTypeToGenerateInWorker(
semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken);
}
return;
}
if (syntaxFacts.IsConditionalAccessExpression(expression))
{
var beforeDotExpression = syntaxFacts.GetExpressionOfConditionalAccessExpression(expression);
if (beforeDotExpression != null)
{
DetermineTypeToGenerateInWorker(
semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken);
if (typeToGenerateIn.IsNullable(out var underlyingType) &&
underlyingType is INamedTypeSymbol underlyingNamedType)
{
typeToGenerateIn = underlyingNamedType;
}
}
return;
}
if (syntaxFacts.IsPointerMemberAccessExpression(expression))
{
var beforeArrowExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression);
if (beforeArrowExpression != null)
{
var typeInfo = semanticModel.GetTypeInfo(beforeArrowExpression, cancellationToken);
if (typeInfo.Type.IsPointerType())
{
typeToGenerateIn = ((IPointerTypeSymbol)typeInfo.Type).PointedAtType as INamedTypeSymbol;
isStatic = false;
}
}
return;
}
if (syntaxFacts.IsAttributeNamedArgumentIdentifier(expression))
{
var attributeNode = expression.GetAncestors().FirstOrDefault(syntaxFacts.IsAttribute);
var attributeName = syntaxFacts.GetNameOfAttribute(attributeNode);
var attributeType = semanticModel.GetTypeInfo(attributeName, cancellationToken);
typeToGenerateIn = attributeType.Type as INamedTypeSymbol;
isStatic = false;
return;
}
if (syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(
expression, out var initializedObject))
{
typeToGenerateIn = semanticModel.GetTypeInfo(initializedObject, cancellationToken).Type as INamedTypeSymbol;
isStatic = false;
return;
}
else if (syntaxFacts.IsNameOfSubpattern(expression))
{
var propertyPatternClause = expression.Ancestors().FirstOrDefault(syntaxFacts.IsPropertyPatternClause);
if (propertyPatternClause != null)
{
// something like: { [|X|]: int i } or like: Blah { [|X|]: int i }
var inferenceService = semanticDocument.Document.GetLanguageService<ITypeInferenceService>();
typeToGenerateIn = inferenceService.InferType(semanticModel, propertyPatternClause, objectAsDefault: true, cancellationToken) as INamedTypeSymbol;
isStatic = false;
return;
}
}
// Generating into the containing type.
typeToGenerateIn = containingType;
isStatic = syntaxFacts.IsInStaticContext(expression);
}
private static void DetermineTypeToGenerateInWorker(
SemanticModel semanticModel,
SyntaxNode expression,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic,
CancellationToken cancellationToken)
{
var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
var semanticInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
typeToGenerateIn = typeInfo.Type is ITypeParameterSymbol typeParameter
? typeParameter.GetNamedTypeSymbolConstraint()
: typeInfo.Type as INamedTypeSymbol;
isStatic = semanticInfo.Symbol is INamedTypeSymbol;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GenerateMember
{
internal abstract partial class AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
{
protected AbstractGenerateMemberService()
{
}
protected static readonly ISet<TypeKind> EnumType = new HashSet<TypeKind> { TypeKind.Enum };
protected static readonly ISet<TypeKind> ClassInterfaceModuleStructTypes = new HashSet<TypeKind>
{
TypeKind.Class,
TypeKind.Module,
TypeKind.Struct,
TypeKind.Interface
};
protected static bool ValidateTypeToGenerateIn(
INamedTypeSymbol typeToGenerateIn,
bool isStatic,
ISet<TypeKind> typeKinds)
{
if (typeToGenerateIn == null)
{
return false;
}
if (typeToGenerateIn.IsAnonymousType)
{
return false;
}
if (!typeKinds.Contains(typeToGenerateIn.TypeKind))
{
return false;
}
if (typeToGenerateIn.TypeKind == TypeKind.Interface && isStatic)
{
return false;
}
// TODO(cyrusn): Make sure that there is a totally visible part somewhere (i.e.
// venus) that we can generate into.
var locations = typeToGenerateIn.Locations;
return locations.Any(loc => loc.IsInSource);
}
protected static bool TryDetermineTypeToGenerateIn(
SemanticDocument document,
INamedTypeSymbol containingType,
TExpressionSyntax simpleNameOrMemberAccessExpression,
CancellationToken cancellationToken,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic)
{
TryDetermineTypeToGenerateInWorker(
document, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out typeToGenerateIn, out isStatic);
if (typeToGenerateIn != null)
{
typeToGenerateIn = typeToGenerateIn.OriginalDefinition;
}
return typeToGenerateIn != null;
}
private static void TryDetermineTypeToGenerateInWorker(
SemanticDocument semanticDocument,
INamedTypeSymbol containingType,
TExpressionSyntax expression,
CancellationToken cancellationToken,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic)
{
typeToGenerateIn = null;
isStatic = false;
var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = semanticDocument.SemanticModel;
if (syntaxFacts.IsSimpleMemberAccessExpression(expression))
{
// Figure out what's before the dot. For VB, that also means finding out
// what ".X" might mean, even when there's nothing before the dot itself.
var beforeDotExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(
expression, allowImplicitTarget: true);
if (beforeDotExpression != null)
{
DetermineTypeToGenerateInWorker(
semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken);
}
return;
}
if (syntaxFacts.IsConditionalAccessExpression(expression))
{
var beforeDotExpression = syntaxFacts.GetExpressionOfConditionalAccessExpression(expression);
if (beforeDotExpression != null)
{
DetermineTypeToGenerateInWorker(
semanticModel, beforeDotExpression, out typeToGenerateIn, out isStatic, cancellationToken);
if (typeToGenerateIn.IsNullable(out var underlyingType) &&
underlyingType is INamedTypeSymbol underlyingNamedType)
{
typeToGenerateIn = underlyingNamedType;
}
}
return;
}
if (syntaxFacts.IsPointerMemberAccessExpression(expression))
{
var beforeArrowExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression);
if (beforeArrowExpression != null)
{
var typeInfo = semanticModel.GetTypeInfo(beforeArrowExpression, cancellationToken);
if (typeInfo.Type.IsPointerType())
{
typeToGenerateIn = ((IPointerTypeSymbol)typeInfo.Type).PointedAtType as INamedTypeSymbol;
isStatic = false;
}
}
return;
}
if (syntaxFacts.IsAttributeNamedArgumentIdentifier(expression))
{
var attributeNode = expression.GetAncestors().FirstOrDefault(syntaxFacts.IsAttribute);
var attributeName = syntaxFacts.GetNameOfAttribute(attributeNode);
var attributeType = semanticModel.GetTypeInfo(attributeName, cancellationToken);
typeToGenerateIn = attributeType.Type as INamedTypeSymbol;
isStatic = false;
return;
}
if (syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(
expression, out var initializedObject))
{
typeToGenerateIn = semanticModel.GetTypeInfo(initializedObject, cancellationToken).Type as INamedTypeSymbol;
isStatic = false;
return;
}
else if (syntaxFacts.IsNameOfSubpattern(expression))
{
var propertyPatternClause = expression.Ancestors().FirstOrDefault(syntaxFacts.IsPropertyPatternClause);
if (propertyPatternClause != null)
{
// something like: { [|X|]: int i } or like: Blah { [|X|]: int i }
var inferenceService = semanticDocument.Document.GetLanguageService<ITypeInferenceService>();
typeToGenerateIn = inferenceService.InferType(semanticModel, propertyPatternClause, objectAsDefault: true, cancellationToken) as INamedTypeSymbol;
isStatic = false;
return;
}
}
// Generating into the containing type.
typeToGenerateIn = containingType;
isStatic = syntaxFacts.IsInStaticContext(expression);
}
private static void DetermineTypeToGenerateInWorker(
SemanticModel semanticModel,
SyntaxNode expression,
out INamedTypeSymbol typeToGenerateIn,
out bool isStatic,
CancellationToken cancellationToken)
{
var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
var semanticInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
typeToGenerateIn = typeInfo.Type is ITypeParameterSymbol typeParameter
? typeParameter.GetNamedTypeSymbolConstraint()
: typeInfo.Type as INamedTypeSymbol;
isStatic = semanticInfo.Symbol is INamedTypeSymbol;
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Core/Portable/Symbols/Attributes/CustomAttributesBag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a bag of custom attributes and the associated decoded well-known attribute data.
/// </summary>
internal sealed class CustomAttributesBag<T>
where T : AttributeData
{
private ImmutableArray<T> _customAttributes;
private WellKnownAttributeData _decodedWellKnownAttributeData;
private EarlyWellKnownAttributeData _earlyDecodedWellKnownAttributeData;
private int _state;
/// <summary>
/// Instance representing sealed custom attribute bag with no attributes.
/// </summary>
public static readonly CustomAttributesBag<T> Empty = new CustomAttributesBag<T>(CustomAttributeBagCompletionPart.All, ImmutableArray<T>.Empty);
private CustomAttributesBag(CustomAttributeBagCompletionPart part, ImmutableArray<T> customAttributes)
{
_customAttributes = customAttributes;
this.NotePartComplete(part);
}
public CustomAttributesBag()
: this(CustomAttributeBagCompletionPart.None, default(ImmutableArray<T>))
{
}
/// <summary>
/// Returns a non-sealed custom attribute bag with null initialized <see cref="_earlyDecodedWellKnownAttributeData"/>, null initialized <see cref="_decodedWellKnownAttributeData"/> and uninitialized <see cref="_customAttributes"/>.
/// </summary>
public static CustomAttributesBag<T> WithEmptyData()
{
return new CustomAttributesBag<T>(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData | CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData, default(ImmutableArray<T>));
}
public bool IsEmpty
{
get
{
return
this.IsSealed &&
_customAttributes.IsEmpty &&
_decodedWellKnownAttributeData == null &&
_earlyDecodedWellKnownAttributeData == null;
}
}
/// <summary>
/// Sets the early decoded well-known attribute data on the bag in a thread safe manner.
/// Stored early decoded data is immutable and cannot be updated further.
/// </summary>
/// <returns>Returns true if early decoded data were stored into the bag on this thread.</returns>
public bool SetEarlyDecodedWellKnownAttributeData(EarlyWellKnownAttributeData data)
{
WellKnownAttributeData.Seal(data);
// Early decode must complete before full decode
Debug.Assert(!IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData) || IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
var setOnOurThread = Interlocked.CompareExchange(ref _earlyDecodedWellKnownAttributeData, data, null) == null;
NotePartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData);
return setOnOurThread;
}
/// <summary>
/// Sets the decoded well-known attribute data (except the early data) on the bag in a thread safe manner.
/// Stored decoded data is immutable and cannot be updated further.
/// </summary>
/// <returns>Returns true if decoded data were stored into the bag on this thread.</returns>
public bool SetDecodedWellKnownAttributeData(WellKnownAttributeData data)
{
WellKnownAttributeData.Seal(data);
// Early decode must complete before full decode
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
var setOnOurThread = Interlocked.CompareExchange(ref _decodedWellKnownAttributeData, data, null) == null;
NotePartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData);
return setOnOurThread;
}
/// <summary>
/// Sets the bound attributes on the bag in a thread safe manner.
/// If store succeeds, it seals the bag and makes the bag immutable.
/// </summary>
/// <returns>Returns true if bound attributes were stored into the bag on this thread.</returns>
public bool SetAttributes(ImmutableArray<T> newCustomAttributes)
{
Debug.Assert(!newCustomAttributes.IsDefault);
var setOnOurThread = ImmutableInterlocked.InterlockedCompareExchange(ref _customAttributes, newCustomAttributes, default(ImmutableArray<T>)) == default(ImmutableArray<T>);
NotePartComplete(CustomAttributeBagCompletionPart.Attributes);
return setOnOurThread;
}
/// <summary>
/// Gets the stored bound attributes in the bag.
/// </summary>
/// <remarks>This property can only be accessed on a sealed bag.</remarks>
public ImmutableArray<T> Attributes
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.Attributes));
Debug.Assert(!_customAttributes.IsDefault);
return _customAttributes;
}
}
/// <summary>
/// Gets the decoded well-known attribute data (except the early data) in the bag.
/// </summary>
/// <remarks>This property can only be accessed on the bag after <see cref="SetDecodedWellKnownAttributeData"/> has been invoked.</remarks>
public WellKnownAttributeData DecodedWellKnownAttributeData
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData));
return _decodedWellKnownAttributeData;
}
}
/// <summary>
/// Gets the early decoded well-known attribute data in the bag.
/// </summary>
/// <remarks>This property can only be accessed on the bag after <see cref="SetEarlyDecodedWellKnownAttributeData"/> has been invoked.</remarks>
public EarlyWellKnownAttributeData EarlyDecodedWellKnownAttributeData
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
return _earlyDecodedWellKnownAttributeData;
}
}
private CustomAttributeBagCompletionPart State
{
get
{
return (CustomAttributeBagCompletionPart)_state;
}
set
{
_state = (int)value;
}
}
private void NotePartComplete(CustomAttributeBagCompletionPart part)
{
ThreadSafeFlagOperations.Set(ref _state, (int)(this.State | part));
}
internal bool IsPartComplete(CustomAttributeBagCompletionPart part)
{
return (this.State & part) == part;
}
internal bool IsSealed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.All); }
}
/// <summary>
/// Return whether early decoded attribute data has been computed and stored on the bag and it is safe to access <see cref="EarlyDecodedWellKnownAttributeData"/> from this bag.
/// Return value of true doesn't guarantee that bound attributes or remaining decoded attribute data has also been initialized.
/// </summary>
internal bool IsEarlyDecodedWellKnownAttributeDataComputed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData); }
}
/// <summary>
/// Return whether all decoded attribute data has been computed and stored on the bag and it is safe to access <see cref="DecodedWellKnownAttributeData"/> from this bag.
/// Return value of true doesn't guarantee that bound attributes have also been initialized.
/// </summary>
internal bool IsDecodedWellKnownAttributeDataComputed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData); }
}
/// <summary>
/// Enum representing the current state of attribute binding/decoding for a corresponding CustomAttributeBag.
/// </summary>
[Flags]
internal enum CustomAttributeBagCompletionPart : byte
{
/// <summary>
/// Bag has been created, but no decoded data or attributes have been stored.
/// CustomAttributeBag is in this state during early decoding phase.
/// </summary>
None = 0,
/// <summary>
/// Early decoded attribute data has been computed and stored on the bag, but bound attributes or remaining decoded attribute data is not stored.
/// Only <see cref="EarlyDecodedWellKnownAttributeData"/> can be accessed from this bag.
/// </summary>
EarlyDecodedWellKnownAttributeData = 1 << 0,
/// <summary>
/// All decoded attribute data has been computed and stored on the bag, but bound attributes are not yet stored.
/// Both <see cref="EarlyDecodedWellKnownAttributeData"/> and <see cref="DecodedWellKnownAttributeData"/> can be accessed from this bag.
/// </summary>
DecodedWellKnownAttributeData = 1 << 1,
/// <summary>
/// Bound attributes have been computed and stored on this bag.
/// </summary>
Attributes = 1 << 2,
/// <summary>
/// CustomAttributeBag is completely initialized and immutable.
/// </summary>
All = EarlyDecodedWellKnownAttributeData | DecodedWellKnownAttributeData | Attributes,
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a bag of custom attributes and the associated decoded well-known attribute data.
/// </summary>
internal sealed class CustomAttributesBag<T>
where T : AttributeData
{
private ImmutableArray<T> _customAttributes;
private WellKnownAttributeData _decodedWellKnownAttributeData;
private EarlyWellKnownAttributeData _earlyDecodedWellKnownAttributeData;
private int _state;
/// <summary>
/// Instance representing sealed custom attribute bag with no attributes.
/// </summary>
public static readonly CustomAttributesBag<T> Empty = new CustomAttributesBag<T>(CustomAttributeBagCompletionPart.All, ImmutableArray<T>.Empty);
private CustomAttributesBag(CustomAttributeBagCompletionPart part, ImmutableArray<T> customAttributes)
{
_customAttributes = customAttributes;
this.NotePartComplete(part);
}
public CustomAttributesBag()
: this(CustomAttributeBagCompletionPart.None, default(ImmutableArray<T>))
{
}
/// <summary>
/// Returns a non-sealed custom attribute bag with null initialized <see cref="_earlyDecodedWellKnownAttributeData"/>, null initialized <see cref="_decodedWellKnownAttributeData"/> and uninitialized <see cref="_customAttributes"/>.
/// </summary>
public static CustomAttributesBag<T> WithEmptyData()
{
return new CustomAttributesBag<T>(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData | CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData, default(ImmutableArray<T>));
}
public bool IsEmpty
{
get
{
return
this.IsSealed &&
_customAttributes.IsEmpty &&
_decodedWellKnownAttributeData == null &&
_earlyDecodedWellKnownAttributeData == null;
}
}
/// <summary>
/// Sets the early decoded well-known attribute data on the bag in a thread safe manner.
/// Stored early decoded data is immutable and cannot be updated further.
/// </summary>
/// <returns>Returns true if early decoded data were stored into the bag on this thread.</returns>
public bool SetEarlyDecodedWellKnownAttributeData(EarlyWellKnownAttributeData data)
{
WellKnownAttributeData.Seal(data);
// Early decode must complete before full decode
Debug.Assert(!IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData) || IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
var setOnOurThread = Interlocked.CompareExchange(ref _earlyDecodedWellKnownAttributeData, data, null) == null;
NotePartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData);
return setOnOurThread;
}
/// <summary>
/// Sets the decoded well-known attribute data (except the early data) on the bag in a thread safe manner.
/// Stored decoded data is immutable and cannot be updated further.
/// </summary>
/// <returns>Returns true if decoded data were stored into the bag on this thread.</returns>
public bool SetDecodedWellKnownAttributeData(WellKnownAttributeData data)
{
WellKnownAttributeData.Seal(data);
// Early decode must complete before full decode
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
var setOnOurThread = Interlocked.CompareExchange(ref _decodedWellKnownAttributeData, data, null) == null;
NotePartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData);
return setOnOurThread;
}
/// <summary>
/// Sets the bound attributes on the bag in a thread safe manner.
/// If store succeeds, it seals the bag and makes the bag immutable.
/// </summary>
/// <returns>Returns true if bound attributes were stored into the bag on this thread.</returns>
public bool SetAttributes(ImmutableArray<T> newCustomAttributes)
{
Debug.Assert(!newCustomAttributes.IsDefault);
var setOnOurThread = ImmutableInterlocked.InterlockedCompareExchange(ref _customAttributes, newCustomAttributes, default(ImmutableArray<T>)) == default(ImmutableArray<T>);
NotePartComplete(CustomAttributeBagCompletionPart.Attributes);
return setOnOurThread;
}
/// <summary>
/// Gets the stored bound attributes in the bag.
/// </summary>
/// <remarks>This property can only be accessed on a sealed bag.</remarks>
public ImmutableArray<T> Attributes
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.Attributes));
Debug.Assert(!_customAttributes.IsDefault);
return _customAttributes;
}
}
/// <summary>
/// Gets the decoded well-known attribute data (except the early data) in the bag.
/// </summary>
/// <remarks>This property can only be accessed on the bag after <see cref="SetDecodedWellKnownAttributeData"/> has been invoked.</remarks>
public WellKnownAttributeData DecodedWellKnownAttributeData
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData));
return _decodedWellKnownAttributeData;
}
}
/// <summary>
/// Gets the early decoded well-known attribute data in the bag.
/// </summary>
/// <remarks>This property can only be accessed on the bag after <see cref="SetEarlyDecodedWellKnownAttributeData"/> has been invoked.</remarks>
public EarlyWellKnownAttributeData EarlyDecodedWellKnownAttributeData
{
get
{
Debug.Assert(IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData));
return _earlyDecodedWellKnownAttributeData;
}
}
private CustomAttributeBagCompletionPart State
{
get
{
return (CustomAttributeBagCompletionPart)_state;
}
set
{
_state = (int)value;
}
}
private void NotePartComplete(CustomAttributeBagCompletionPart part)
{
ThreadSafeFlagOperations.Set(ref _state, (int)(this.State | part));
}
internal bool IsPartComplete(CustomAttributeBagCompletionPart part)
{
return (this.State & part) == part;
}
internal bool IsSealed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.All); }
}
/// <summary>
/// Return whether early decoded attribute data has been computed and stored on the bag and it is safe to access <see cref="EarlyDecodedWellKnownAttributeData"/> from this bag.
/// Return value of true doesn't guarantee that bound attributes or remaining decoded attribute data has also been initialized.
/// </summary>
internal bool IsEarlyDecodedWellKnownAttributeDataComputed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.EarlyDecodedWellKnownAttributeData); }
}
/// <summary>
/// Return whether all decoded attribute data has been computed and stored on the bag and it is safe to access <see cref="DecodedWellKnownAttributeData"/> from this bag.
/// Return value of true doesn't guarantee that bound attributes have also been initialized.
/// </summary>
internal bool IsDecodedWellKnownAttributeDataComputed
{
get { return IsPartComplete(CustomAttributeBagCompletionPart.DecodedWellKnownAttributeData); }
}
/// <summary>
/// Enum representing the current state of attribute binding/decoding for a corresponding CustomAttributeBag.
/// </summary>
[Flags]
internal enum CustomAttributeBagCompletionPart : byte
{
/// <summary>
/// Bag has been created, but no decoded data or attributes have been stored.
/// CustomAttributeBag is in this state during early decoding phase.
/// </summary>
None = 0,
/// <summary>
/// Early decoded attribute data has been computed and stored on the bag, but bound attributes or remaining decoded attribute data is not stored.
/// Only <see cref="EarlyDecodedWellKnownAttributeData"/> can be accessed from this bag.
/// </summary>
EarlyDecodedWellKnownAttributeData = 1 << 0,
/// <summary>
/// All decoded attribute data has been computed and stored on the bag, but bound attributes are not yet stored.
/// Both <see cref="EarlyDecodedWellKnownAttributeData"/> and <see cref="DecodedWellKnownAttributeData"/> can be accessed from this bag.
/// </summary>
DecodedWellKnownAttributeData = 1 << 1,
/// <summary>
/// Bound attributes have been computed and stored on this bag.
/// </summary>
Attributes = 1 << 2,
/// <summary>
/// CustomAttributeBag is completely initialized and immutable.
/// </summary>
All = EarlyDecodedWellKnownAttributeData | DecodedWellKnownAttributeData | Attributes,
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/VisualStudio/Core/Def/Interactive/LogMessage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
internal static class LogMessage
{
public const string Window = "InteractiveWindow";
public const string Create = nameof(Create);
public const string Close = nameof(Close);
public const string LanguageBufferCount = nameof(LanguageBufferCount);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
internal static class LogMessage
{
public const string Window = "InteractiveWindow";
public const string Create = nameof(Create);
public const string Close = nameof(Close);
public const string LanguageBufferCount = nameof(LanguageBufferCount);
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenInterfaceImplementation.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenInterfaceImplementationTests
Inherits BasicTestBase
<WorkItem(540794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540794")>
<Fact>
Public Sub TestInterfaceMembersSignature()
Dim source =
<compilation>
<file name="a.vb">
Interface IFace
Sub SubRoutine()
Function Func() As Integer
Property Prop As Integer
End Interface
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("IFace", "SubRoutine", ".method public newslot strict abstract virtual instance System.Void SubRoutine() cil managed"),
Signature("IFace", "Func", ".method public newslot strict abstract virtual instance System.Int32 Func() cil managed"),
Signature("IFace", "get_Prop", ".method public newslot strict specialname abstract virtual instance System.Int32 get_Prop() cil managed"),
Signature("IFace", "set_Prop", ".method public newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32 Value) cil managed"),
Signature("IFace", "Prop", ".property readwrite instance System.Int32 Prop")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540794")>
<WorkItem(540805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540805")>
<WorkItem(540861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540861")>
<WorkItem(540807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540807")>
<Fact>
Public Sub TestNestedInterface()
Dim source =
<compilation>
<file name="a.vb">
Class Class2
Implements Class2.InterfaceDerived
Interface InterfaceDerived
Inherits Class2.InterfaceBase
Sub AbcDef()
End Interface
Public Interface InterfaceBase
Property Bar As Integer
End Interface
Public Property Bar As Integer Implements InterfaceDerived.Bar
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public Sub AbcDef() Implements InterfaceDerived.AbcDef
End Sub
End Class
Class Class1
Implements Class1.Interface1
Public Interface Interface1
Sub Goo()
End Interface
Public Sub Goo() Implements Interface1.Goo
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("Class2+InterfaceBase", "get_Bar", ".method public newslot strict specialname abstract virtual instance System.Int32 get_Bar() cil managed"),
Signature("Class2+InterfaceBase", "set_Bar", ".method public newslot strict specialname abstract virtual instance System.Void set_Bar(System.Int32 Value) cil managed"),
Signature("Class2+InterfaceBase", "Bar", ".property readwrite instance System.Int32 Bar"),
Signature("Class2+InterfaceDerived", "AbcDef", ".method public newslot strict abstract virtual instance System.Void AbcDef() cil managed"),
Signature("Class2", "get_Bar", ".method public newslot strict specialname virtual final instance System.Int32 get_Bar() cil managed"),
Signature("Class2", "set_Bar", ".method public newslot strict specialname virtual final instance System.Void set_Bar(System.Int32 value) cil managed"),
Signature("Class2", "AbcDef", ".method public newslot strict virtual final instance System.Void AbcDef() cil managed"),
Signature("Class2", "Bar", ".property readwrite instance System.Int32 Bar"),
Signature("Class1+Interface1", "Goo", ".method public newslot strict abstract virtual instance System.Void Goo() cil managed"),
Signature("Class1", "Goo", ".method public newslot strict virtual final instance System.Void Goo() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")>
<Fact()>
Public Sub TestExplicitlyImplementInterfaceNestedInGenericType()
Dim source =
<compilation>
<file name="a.vb">
Class Outer(Of T)
Interface IInner
Sub M(t As T)
End Interface
Class Inner
Implements IInner
Private Sub M(t As T) Implements Outer(Of T).IInner.M
End Sub
End Class
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("Outer`1+IInner", "M", ".method public newslot strict abstract virtual instance System.Void M(T t) cil managed"),
Signature("Outer`1+Inner", "M", ".method private newslot strict virtual final instance System.Void M(T t) cil managed")
})
verifier.VerifyDiagnostics()
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenInterfaceImplementationTests
Inherits BasicTestBase
<WorkItem(540794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540794")>
<Fact>
Public Sub TestInterfaceMembersSignature()
Dim source =
<compilation>
<file name="a.vb">
Interface IFace
Sub SubRoutine()
Function Func() As Integer
Property Prop As Integer
End Interface
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("IFace", "SubRoutine", ".method public newslot strict abstract virtual instance System.Void SubRoutine() cil managed"),
Signature("IFace", "Func", ".method public newslot strict abstract virtual instance System.Int32 Func() cil managed"),
Signature("IFace", "get_Prop", ".method public newslot strict specialname abstract virtual instance System.Int32 get_Prop() cil managed"),
Signature("IFace", "set_Prop", ".method public newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32 Value) cil managed"),
Signature("IFace", "Prop", ".property readwrite instance System.Int32 Prop")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540794")>
<WorkItem(540805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540805")>
<WorkItem(540861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540861")>
<WorkItem(540807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540807")>
<Fact>
Public Sub TestNestedInterface()
Dim source =
<compilation>
<file name="a.vb">
Class Class2
Implements Class2.InterfaceDerived
Interface InterfaceDerived
Inherits Class2.InterfaceBase
Sub AbcDef()
End Interface
Public Interface InterfaceBase
Property Bar As Integer
End Interface
Public Property Bar As Integer Implements InterfaceDerived.Bar
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public Sub AbcDef() Implements InterfaceDerived.AbcDef
End Sub
End Class
Class Class1
Implements Class1.Interface1
Public Interface Interface1
Sub Goo()
End Interface
Public Sub Goo() Implements Interface1.Goo
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("Class2+InterfaceBase", "get_Bar", ".method public newslot strict specialname abstract virtual instance System.Int32 get_Bar() cil managed"),
Signature("Class2+InterfaceBase", "set_Bar", ".method public newslot strict specialname abstract virtual instance System.Void set_Bar(System.Int32 Value) cil managed"),
Signature("Class2+InterfaceBase", "Bar", ".property readwrite instance System.Int32 Bar"),
Signature("Class2+InterfaceDerived", "AbcDef", ".method public newslot strict abstract virtual instance System.Void AbcDef() cil managed"),
Signature("Class2", "get_Bar", ".method public newslot strict specialname virtual final instance System.Int32 get_Bar() cil managed"),
Signature("Class2", "set_Bar", ".method public newslot strict specialname virtual final instance System.Void set_Bar(System.Int32 value) cil managed"),
Signature("Class2", "AbcDef", ".method public newslot strict virtual final instance System.Void AbcDef() cil managed"),
Signature("Class2", "Bar", ".property readwrite instance System.Int32 Bar"),
Signature("Class1+Interface1", "Goo", ".method public newslot strict abstract virtual instance System.Void Goo() cil managed"),
Signature("Class1", "Goo", ".method public newslot strict virtual final instance System.Void Goo() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")>
<Fact()>
Public Sub TestExplicitlyImplementInterfaceNestedInGenericType()
Dim source =
<compilation>
<file name="a.vb">
Class Outer(Of T)
Interface IInner
Sub M(t As T)
End Interface
Class Inner
Implements IInner
Private Sub M(t As T) Implements Outer(Of T).IInner.M
End Sub
End Class
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("Outer`1+IInner", "M", ".method public newslot strict abstract virtual instance System.Void M(T t) cil managed"),
Signature("Outer`1+Inner", "M", ".method private newslot strict virtual final instance System.Void M(T t) cil managed")
})
verifier.VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Workspaces/Core/Portable/EmbeddedLanguages/LanguageServices/IEmbeddedLanguage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices
{
/// <summary>
/// Services related to a specific embedded language.
/// </summary>
internal interface IEmbeddedLanguage
{
/// <summary>
/// A optional classifier that can produce <see cref="ClassifiedSpan"/>s for an embedded language string.
/// </summary>
ISyntaxClassifier Classifier { 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 Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices
{
/// <summary>
/// Services related to a specific embedded language.
/// </summary>
internal interface IEmbeddedLanguage
{
/// <summary>
/// A optional classifier that can produce <see cref="ClassifiedSpan"/>s for an embedded language string.
/// </summary>
ISyntaxClassifier Classifier { get; }
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Compilers/Test/Core/PDB/DeterministicBuildCompilationTestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Roslyn.Test.Utilities.PDB
{
internal static partial class DeterministicBuildCompilationTestHelpers
{
public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null)
{
bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default);
var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString();
pdbOptions.TryGetValue(pdbName, out var actualValueString);
Assert.Equal(expectedValueString, actualValueString);
}
public static IEnumerable<EmitOptions> GetEmitOptions()
{
var emitOptions = new EmitOptions(
debugInformationFormat: DebugInformationFormat.Embedded,
pdbChecksumAlgorithm: HashAlgorithmName.SHA256,
defaultSourceFileEncoding: Encoding.UTF32);
yield return emitOptions;
yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII);
yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode);
yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII);
}
internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions)
{
pdbOptions.VerifyPdbOption("version", 2);
pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName);
pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName);
int portabilityPolicy = 0;
if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy);
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]);
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]);
pdbOptions.VerifyPdbOption(
"optimization",
(compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode),
toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode));
Assert.Equal(compilation.Language, pdbOptions["language"]);
}
public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader)
{
var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework);
var count = 0;
while (metadataReferenceReader.RemainingBytes > 0)
{
var info = ParseMetadataReferenceInfo(ref metadataReferenceReader);
if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid))
{
count++;
continue;
}
var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid);
testReference.MetadataReferenceInfo.AssertEqual(info);
count++;
}
Assert.Equal(references.Length + frameworkReferences.Length, count);
}
public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader)
{
return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == infoGuid
select pdbReader.GetBlobReader(cdi.Value)).Single();
}
public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
return new MetadataReferenceInfo(
timestamp,
imageSize,
name,
mvid,
string.IsNullOrEmpty(externAliases)
? ImmutableArray<string>.Empty
: externAliases.Split(',').ToImmutableArray(),
kind,
embedInteropTypes);
}
public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader)
{
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
string key = null;
Dictionary<string, string> kvp = new Dictionary<string, string>();
for (; ; )
{
var nullIndex = blobReader.IndexOf(0);
if (nullIndex == -1)
{
break;
}
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
if (key is null)
{
key = value;
}
else
{
kvp[key] = value;
key = null;
}
}
Assert.Null(key);
Assert.Equal(0, blobReader.RemainingBytes);
return kvp.ToImmutableDictionary();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Roslyn.Test.Utilities.PDB
{
internal static partial class DeterministicBuildCompilationTestHelpers
{
public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null)
{
bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default);
var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString();
pdbOptions.TryGetValue(pdbName, out var actualValueString);
Assert.Equal(expectedValueString, actualValueString);
}
public static IEnumerable<EmitOptions> GetEmitOptions()
{
var emitOptions = new EmitOptions(
debugInformationFormat: DebugInformationFormat.Embedded,
pdbChecksumAlgorithm: HashAlgorithmName.SHA256,
defaultSourceFileEncoding: Encoding.UTF32);
yield return emitOptions;
yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII);
yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode);
yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII);
}
internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions)
{
pdbOptions.VerifyPdbOption("version", 2);
pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName);
pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName);
int portabilityPolicy = 0;
if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy);
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]);
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]);
pdbOptions.VerifyPdbOption(
"optimization",
(compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode),
toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode));
Assert.Equal(compilation.Language, pdbOptions["language"]);
}
public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader)
{
var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework);
var count = 0;
while (metadataReferenceReader.RemainingBytes > 0)
{
var info = ParseMetadataReferenceInfo(ref metadataReferenceReader);
if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid))
{
count++;
continue;
}
var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid);
testReference.MetadataReferenceInfo.AssertEqual(info);
count++;
}
Assert.Equal(references.Length + frameworkReferences.Length, count);
}
public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader)
{
return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == infoGuid
select pdbReader.GetBlobReader(cdi.Value)).Single();
}
public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
return new MetadataReferenceInfo(
timestamp,
imageSize,
name,
mvid,
string.IsNullOrEmpty(externAliases)
? ImmutableArray<string>.Empty
: externAliases.Split(',').ToImmutableArray(),
kind,
embedInteropTypes);
}
public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader)
{
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
string key = null;
Dictionary<string, string> kvp = new Dictionary<string, string>();
for (; ; )
{
var nullIndex = blobReader.IndexOf(0);
if (nullIndex == -1)
{
break;
}
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
if (key is null)
{
key = value;
}
else
{
kvp[key] = value;
key = null;
}
}
Assert.Null(key);
Assert.Equal(0, blobReader.RemainingBytes);
return kvp.ToImmutableDictionary();
}
}
}
| -1 |
dotnet/roslyn | 56,351 | Follow syntaxfacts pattern | I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | CyrusNajmabadi | "2021-09-13T17:58:02Z" | "2021-09-15T23:37:04Z" | 5aa5223fc3a55b6c4ec91694aafa71c918e368e8 | 3f2908b43d85793d386181ab785712705568c053 | Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77 | ./src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression
{
[ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.CSharp), Shared]
internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSuppressionCodeFixProvider()
{
}
protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword);
return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia(
Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword);
return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
private static SyntaxTriviaList CreatePragmaDirectiveTrivia(
SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var diagnosticId = GetOrMapDiagnosticId(diagnostic, out var includeTitle);
var id = SyntaxFactory.IdentifierName(diagnosticId);
var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)formatNode(pragmaDirective);
var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective);
var endOfLineTrivia = SyntaxFactory.CarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);
var title = includeTitle ? diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) : null;
if (!string.IsNullOrWhiteSpace(title))
{
var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
triviaList = triviaList.Add(titleComment);
}
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Insert(0, endOfLineTrivia);
}
if (needsTrailingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return triviaList;
}
protected override string DefaultFileExtension => ".cs";
protected override string SingleLineCommentStart => "//";
protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node)
{
return node is AttributeListSyntax attributeList &&
attributeList.Target != null &&
attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword;
}
protected override bool IsEndOfLine(SyntaxTrivia trivia)
=> trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia);
protected override bool IsEndOfFileToken(SyntaxToken token)
=> token.Kind() == SyntaxKind.EndOfFileToken;
protected override SyntaxNode AddGlobalSuppressMessageAttribute(
SyntaxNode newRoot,
ISymbol targetSymbol,
INamedTypeSymbol suppressMessageAttribute,
Diagnostic diagnostic,
Workspace workspace,
Compilation compilation,
IAddImportsService addImportsService,
CancellationToken cancellationToken)
{
var compilationRoot = (CompilationUnitSyntax)newRoot;
var isFirst = !compilationRoot.AttributeLists.Any();
var attributeName = suppressMessageAttribute.GenerateNameSyntax()
.WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
compilationRoot = compilationRoot.AddAttributeLists(
CreateAttributeList(
targetSymbol,
attributeName,
diagnostic,
isAssemblyAttribute: true,
leadingTrivia: default,
needsLeadingEndOfLine: true));
if (isFirst && !newRoot.HasLeadingTrivia)
compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment));
return compilationRoot;
}
protected override SyntaxNode AddLocalSuppressMessageAttribute(
SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic)
{
var memberNode = (MemberDeclarationSyntax)targetNode;
SyntaxTriviaList leadingTriviaForAttributeList;
bool needsLeadingEndOfLine;
if (!memberNode.GetAttributes().Any())
{
leadingTriviaForAttributeList = memberNode.GetLeadingTrivia();
memberNode = memberNode.WithoutLeadingTrivia();
needsLeadingEndOfLine = !leadingTriviaForAttributeList.Any() || !IsEndOfLine(leadingTriviaForAttributeList.Last());
}
else
{
leadingTriviaForAttributeList = default;
needsLeadingEndOfLine = true;
}
var attributeName = suppressMessageAttribute.GenerateNameSyntax();
var attributeList = CreateAttributeList(
targetSymbol, attributeName, diagnostic, isAssemblyAttribute: false, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: needsLeadingEndOfLine);
return memberNode.AddAttributeLists(attributeList);
}
private static AttributeListSyntax CreateAttributeList(
ISymbol targetSymbol,
NameSyntax attributeName,
Diagnostic diagnostic,
bool isAssemblyAttribute,
SyntaxTriviaList leadingTrivia,
bool needsLeadingEndOfLine)
{
var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute);
var attributes = new SeparatedSyntaxList<AttributeSyntax>()
.Add(SyntaxFactory.Attribute(attributeName, attributeArguments));
AttributeListSyntax attributeList;
if (isAssemblyAttribute)
{
var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
}
else
{
attributeList = SyntaxFactory.AttributeList(attributes);
}
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList();
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList));
}
private static AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute)
{
// SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target))
var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category));
var categoryArgument = SyntaxFactory.AttributeArgument(category);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title);
var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText));
var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId);
var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending));
var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr);
var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument);
if (isAssemblyAttribute)
{
var scopeString = GetScopeString(targetSymbol.Kind);
if (scopeString != null)
{
var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString));
var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr);
var targetString = GetTargetString(targetSymbol);
var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString));
var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr);
attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument);
}
}
return attributeArgumentList;
}
protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute)
{
if (attribute is AttributeSyntax attributeSyntax)
{
return attributeSyntax.Parent is AttributeListSyntax attributeList && attributeList.Attributes.Count == 1;
}
return false;
}
protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds)
{
if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword;
hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1;
return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id);
}
enableDirective = false;
hasMultipleIds = false;
return false;
}
protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
var currentKeyword = pragmaWarning.DisableOrRestoreKeyword;
var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword;
var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia);
var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken);
return SyntaxFactory.Trivia(newPragmaWarning);
}
protected override SyntaxToken GetAdjustedTokenForPragmaRestore(
SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine)
{
var nextToken = token.GetNextToken();
if (nextToken.Kind() == SyntaxKind.SemicolonToken &&
nextToken.Parent is StatementSyntax statement &&
statement.GetLastToken() == nextToken &&
token.Parent.FirstAncestorOrSelf<StatementSyntax>() == statement)
{
// both the current and next tokens belong to the same statement, and the next token
// is the final semicolon in a statement. Do not put the pragma before that
// semicolon. Place it after the semicolon so the statement stays whole.
return nextToken;
}
return token;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression
{
[ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.CSharp), Shared]
internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSuppressionCodeFixProvider()
{
}
protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword);
return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia(
Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword);
return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine);
}
private static SyntaxTriviaList CreatePragmaDirectiveTrivia(
SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var diagnosticId = GetOrMapDiagnosticId(diagnostic, out var includeTitle);
var id = SyntaxFactory.IdentifierName(diagnosticId);
var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)formatNode(pragmaDirective);
var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective);
var endOfLineTrivia = SyntaxFactory.CarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);
var title = includeTitle ? diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) : null;
if (!string.IsNullOrWhiteSpace(title))
{
var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
triviaList = triviaList.Add(titleComment);
}
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Insert(0, endOfLineTrivia);
}
if (needsTrailingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return triviaList;
}
protected override string DefaultFileExtension => ".cs";
protected override string SingleLineCommentStart => "//";
protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node)
{
return node is AttributeListSyntax attributeList &&
attributeList.Target != null &&
attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword;
}
protected override bool IsEndOfLine(SyntaxTrivia trivia)
=> trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia);
protected override bool IsEndOfFileToken(SyntaxToken token)
=> token.Kind() == SyntaxKind.EndOfFileToken;
protected override SyntaxNode AddGlobalSuppressMessageAttribute(
SyntaxNode newRoot,
ISymbol targetSymbol,
INamedTypeSymbol suppressMessageAttribute,
Diagnostic diagnostic,
Workspace workspace,
Compilation compilation,
IAddImportsService addImportsService,
CancellationToken cancellationToken)
{
var compilationRoot = (CompilationUnitSyntax)newRoot;
var isFirst = !compilationRoot.AttributeLists.Any();
var attributeName = suppressMessageAttribute.GenerateNameSyntax()
.WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
compilationRoot = compilationRoot.AddAttributeLists(
CreateAttributeList(
targetSymbol,
attributeName,
diagnostic,
isAssemblyAttribute: true,
leadingTrivia: default,
needsLeadingEndOfLine: true));
if (isFirst && !newRoot.HasLeadingTrivia)
compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment));
return compilationRoot;
}
protected override SyntaxNode AddLocalSuppressMessageAttribute(
SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic)
{
var memberNode = (MemberDeclarationSyntax)targetNode;
SyntaxTriviaList leadingTriviaForAttributeList;
bool needsLeadingEndOfLine;
if (!memberNode.GetAttributes().Any())
{
leadingTriviaForAttributeList = memberNode.GetLeadingTrivia();
memberNode = memberNode.WithoutLeadingTrivia();
needsLeadingEndOfLine = !leadingTriviaForAttributeList.Any() || !IsEndOfLine(leadingTriviaForAttributeList.Last());
}
else
{
leadingTriviaForAttributeList = default;
needsLeadingEndOfLine = true;
}
var attributeName = suppressMessageAttribute.GenerateNameSyntax();
var attributeList = CreateAttributeList(
targetSymbol, attributeName, diagnostic, isAssemblyAttribute: false, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: needsLeadingEndOfLine);
return memberNode.AddAttributeLists(attributeList);
}
private static AttributeListSyntax CreateAttributeList(
ISymbol targetSymbol,
NameSyntax attributeName,
Diagnostic diagnostic,
bool isAssemblyAttribute,
SyntaxTriviaList leadingTrivia,
bool needsLeadingEndOfLine)
{
var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute);
var attributes = new SeparatedSyntaxList<AttributeSyntax>()
.Add(SyntaxFactory.Attribute(attributeName, attributeArguments));
AttributeListSyntax attributeList;
if (isAssemblyAttribute)
{
var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
}
else
{
attributeList = SyntaxFactory.AttributeList(attributes);
}
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList();
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList));
}
private static AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute)
{
// SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target))
var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category));
var categoryArgument = SyntaxFactory.AttributeArgument(category);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title);
var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText));
var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId);
var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending));
var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr);
var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument);
if (isAssemblyAttribute)
{
var scopeString = GetScopeString(targetSymbol.Kind);
if (scopeString != null)
{
var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString));
var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr);
var targetString = GetTargetString(targetSymbol);
var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString));
var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr);
attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument);
}
}
return attributeArgumentList;
}
protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute)
{
if (attribute is AttributeSyntax attributeSyntax)
{
return attributeSyntax.Parent is AttributeListSyntax attributeList && attributeList.Attributes.Count == 1;
}
return false;
}
protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds)
{
if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword;
hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1;
return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id);
}
enableDirective = false;
hasMultipleIds = false;
return false;
}
protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia)
{
var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure();
var currentKeyword = pragmaWarning.DisableOrRestoreKeyword;
var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword;
var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia);
var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken);
return SyntaxFactory.Trivia(newPragmaWarning);
}
protected override SyntaxToken GetAdjustedTokenForPragmaRestore(
SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine)
{
var nextToken = token.GetNextToken();
if (nextToken.Kind() == SyntaxKind.SemicolonToken &&
nextToken.Parent is StatementSyntax statement &&
statement.GetLastToken() == nextToken &&
token.Parent.FirstAncestorOrSelf<StatementSyntax>() == statement)
{
// both the current and next tokens belong to the same statement, and the next token
// is the final semicolon in a statement. Do not put the pragma before that
// semicolon. Place it after the semicolon so the statement stays whole.
return nextToken;
}
return token;
}
}
}
| -1 |
Subsets and Splits