repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.GenerateFinalizerItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateFinalizer : AbstractGenerateCodeItem
{
public GenerateFinalizer(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateFinalizer, text, Glyph.MethodProtected, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateFinalizer(Text, DestinationTypeSymbolKey);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateFinalizer : AbstractGenerateCodeItem
{
public GenerateFinalizer(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateFinalizer, text, Glyph.MethodProtected, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateFinalizer(Text, DestinationTypeSymbolKey);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/FusionAssemblyIdentityComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.UnitTests
{
internal sealed class FusionAssemblyIdentityComparer
{
// internal for testing
internal enum AssemblyComparisonResult
{
Unknown = 0,
EquivalentFullMatch = 1, // all fields match
EquivalentWeakNamed = 2, // match based on weak-name, version numbers ignored
EquivalentFxUnified = 3, // match based on FX-unification of version numbers
EquivalentUnified = 4, // match based on legacy-unification of version numbers
NonEquivalentVersion = 5, // all fields match except version field
NonEquivalent = 6, // no match
EquivalentPartialMatch = 7,
EquivalentPartialWeakNamed = 8,
EquivalentPartialUnified = 9,
EquivalentPartialFxUnified = 10,
NonEquivalentPartialVersion = 11
}
private static readonly object s_assemblyIdentityGate = new object();
internal static AssemblyIdentityComparer.ComparisonResult CompareAssemblyIdentity(string fullName1, string fullName2, bool ignoreVersion, FusionAssemblyPortabilityPolicy policy, out bool unificationApplied)
{
unificationApplied = false;
bool equivalent;
AssemblyComparisonResult result;
IntPtr asmConfigCookie = policy == null ? IntPtr.Zero : policy.ConfigCookie;
int hr = DefaultModelCompareAssemblyIdentity(fullName1, ignoreVersion, fullName2, ignoreVersion, out equivalent, out result, asmConfigCookie);
if (hr != 0 || !equivalent)
{
return AssemblyIdentityComparer.ComparisonResult.NotEquivalent;
}
switch (result)
{
case AssemblyComparisonResult.EquivalentFullMatch:
// all properties match
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentWeakNamed:
// both names are weak (have no public key token) and their simple names match:
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentFxUnified:
// Framework assembly with unified version.
unificationApplied = true;
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentUnified:
// Strong named, all properties but version match.
Debug.Assert(ignoreVersion);
return AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion;
default:
// Partial name was specified:
return equivalent ? AssemblyIdentityComparer.ComparisonResult.Equivalent : AssemblyIdentityComparer.ComparisonResult.NotEquivalent;
}
}
internal static int DefaultModelCompareAssemblyIdentity(
string identity1,
bool isUnified1,
string identity2,
bool isUnified2,
out bool areEquivalent,
out AssemblyComparisonResult result,
IntPtr asmConfigCookie)
{
lock (s_assemblyIdentityGate)
{
return CompareAssemblyIdentityWithConfig(
identity1,
isUnified1,
identity2,
isUnified2,
asmConfigCookie,
out areEquivalent,
out result);
}
}
// internal for testing
[DllImport("clr", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int CompareAssemblyIdentityWithConfig(
[MarshalAs(UnmanagedType.LPWStr)] string identity1,
bool isUnified1,
[MarshalAs(UnmanagedType.LPWStr)] string identity2,
bool isUnified2,
IntPtr asmConfigCookie,
out bool areEquivalent,
out AssemblyComparisonResult result);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.UnitTests
{
internal sealed class FusionAssemblyIdentityComparer
{
// internal for testing
internal enum AssemblyComparisonResult
{
Unknown = 0,
EquivalentFullMatch = 1, // all fields match
EquivalentWeakNamed = 2, // match based on weak-name, version numbers ignored
EquivalentFxUnified = 3, // match based on FX-unification of version numbers
EquivalentUnified = 4, // match based on legacy-unification of version numbers
NonEquivalentVersion = 5, // all fields match except version field
NonEquivalent = 6, // no match
EquivalentPartialMatch = 7,
EquivalentPartialWeakNamed = 8,
EquivalentPartialUnified = 9,
EquivalentPartialFxUnified = 10,
NonEquivalentPartialVersion = 11
}
private static readonly object s_assemblyIdentityGate = new object();
internal static AssemblyIdentityComparer.ComparisonResult CompareAssemblyIdentity(string fullName1, string fullName2, bool ignoreVersion, FusionAssemblyPortabilityPolicy policy, out bool unificationApplied)
{
unificationApplied = false;
bool equivalent;
AssemblyComparisonResult result;
IntPtr asmConfigCookie = policy == null ? IntPtr.Zero : policy.ConfigCookie;
int hr = DefaultModelCompareAssemblyIdentity(fullName1, ignoreVersion, fullName2, ignoreVersion, out equivalent, out result, asmConfigCookie);
if (hr != 0 || !equivalent)
{
return AssemblyIdentityComparer.ComparisonResult.NotEquivalent;
}
switch (result)
{
case AssemblyComparisonResult.EquivalentFullMatch:
// all properties match
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentWeakNamed:
// both names are weak (have no public key token) and their simple names match:
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentFxUnified:
// Framework assembly with unified version.
unificationApplied = true;
return AssemblyIdentityComparer.ComparisonResult.Equivalent;
case AssemblyComparisonResult.EquivalentUnified:
// Strong named, all properties but version match.
Debug.Assert(ignoreVersion);
return AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion;
default:
// Partial name was specified:
return equivalent ? AssemblyIdentityComparer.ComparisonResult.Equivalent : AssemblyIdentityComparer.ComparisonResult.NotEquivalent;
}
}
internal static int DefaultModelCompareAssemblyIdentity(
string identity1,
bool isUnified1,
string identity2,
bool isUnified2,
out bool areEquivalent,
out AssemblyComparisonResult result,
IntPtr asmConfigCookie)
{
lock (s_assemblyIdentityGate)
{
return CompareAssemblyIdentityWithConfig(
identity1,
isUnified1,
identity2,
isUnified2,
asmConfigCookie,
out areEquivalent,
out result);
}
}
// internal for testing
[DllImport("clr", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int CompareAssemblyIdentityWithConfig(
[MarshalAs(UnmanagedType.LPWStr)] string identity1,
bool isUnified1,
[MarshalAs(UnmanagedType.LPWStr)] string identity2,
bool isUnified2,
IntPtr asmConfigCookie,
out bool areEquivalent,
out AssemblyComparisonResult result);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/Core/Analyzers/Helpers/DiagnosticHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class DiagnosticHelper
{
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
LocalizableString message;
if (messageArgs == null || messageArgs.Length == 0)
{
message = descriptor.MessageFormat;
}
else
{
message = new LocalizableStringWithArguments(descriptor.MessageFormat, messageArgs);
}
return CreateWithMessage(descriptor, location, effectiveSeverity, additionalLocations, properties, message);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
ImmutableDictionary<string, string>.Empty,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
properties,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// </param>
/// <param name="tagIndices">
/// a map of location tag to index in additional locations.
/// "AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer" for an example of usage.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
private static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
IDictionary<string, IEnumerable<int>> tagIndices,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
Contract.ThrowIfTrue(additionalLocations.IsEmpty());
Contract.ThrowIfTrue(tagIndices.IsEmpty());
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.AddRange(tagIndices.Select(kvp => new KeyValuePair<string, string>(kvp.Key, EncodeIndices(kvp.Value, additionalLocations.Count()))));
return Create(descriptor, location, effectiveSeverity, additionalLocations, properties, messageArgs);
static string EncodeIndices(IEnumerable<int> indices, int additionalLocationsLength)
{
// Ensure that the provided tag index is a valid index into additional locations.
Contract.ThrowIfFalse(indices.All(idx => idx >= 0 && idx < additionalLocationsLength));
using var stream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>));
serializer.WriteObject(stream, indices);
var jsonBytes = stream.ToArray();
stream.Close();
return Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
}
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="message">Localizable message for the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithMessage(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
LocalizableString message)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
return Diagnostic.Create(
descriptor.Id,
descriptor.Category,
message,
effectiveSeverity.ToDiagnosticSeverity() ?? descriptor.DefaultSeverity,
descriptor.DefaultSeverity,
descriptor.IsEnabledByDefault,
warningLevel: effectiveSeverity.WithDefaultSeverity(descriptor.DefaultSeverity) == ReportDiagnostic.Error ? 0 : 1,
effectiveSeverity == ReportDiagnostic.Suppress,
descriptor.Title,
descriptor.Description,
descriptor.HelpLinkUri,
location,
additionalLocations,
descriptor.CustomTags,
properties);
}
public static string GetHelpLinkForDiagnosticId(string id)
{
if (id == "RE0001")
{
// TODO: Add documentation for Regex analyzer
// Tracked with https://github.com/dotnet/roslyn/issues/48530
return null;
}
Debug.Assert(id.StartsWith("IDE", StringComparison.Ordinal));
return $"https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/{id.ToLowerInvariant()}";
}
public sealed class LocalizableStringWithArguments : LocalizableString, IObjectWritable
{
private readonly LocalizableString _messageFormat;
private readonly string[] _formatArguments;
static LocalizableStringWithArguments()
=> ObjectBinder.RegisterTypeReader(typeof(LocalizableStringWithArguments), reader => new LocalizableStringWithArguments(reader));
public LocalizableStringWithArguments(LocalizableString messageFormat, params object[] formatArguments)
{
if (messageFormat == null)
{
throw new ArgumentNullException(nameof(messageFormat));
}
if (formatArguments == null)
{
throw new ArgumentNullException(nameof(formatArguments));
}
_messageFormat = messageFormat;
_formatArguments = new string[formatArguments.Length];
for (var i = 0; i < formatArguments.Length; i++)
{
_formatArguments[i] = $"{formatArguments[i]}";
}
}
private LocalizableStringWithArguments(ObjectReader reader)
{
_messageFormat = (LocalizableString)reader.ReadValue();
var length = reader.ReadInt32();
if (length == 0)
{
_formatArguments = Array.Empty<string>();
}
else
{
using var argumentsBuilderDisposer = ArrayBuilder<string>.GetInstance(length, out var argumentsBuilder);
for (var i = 0; i < length; i++)
{
argumentsBuilder.Add(reader.ReadString());
}
_formatArguments = argumentsBuilder.ToArray();
}
}
bool IObjectWritable.ShouldReuseInSerialization => false;
void IObjectWritable.WriteTo(ObjectWriter writer)
{
writer.WriteValue(_messageFormat);
var length = _formatArguments.Length;
writer.WriteInt32(length);
for (var i = 0; i < length; i++)
{
writer.WriteString(_formatArguments[i]);
}
}
protected override string GetText(IFormatProvider formatProvider)
{
var messageFormat = _messageFormat.ToString(formatProvider);
return messageFormat != null ?
(_formatArguments.Length > 0 ? string.Format(formatProvider, messageFormat, _formatArguments) : messageFormat) :
string.Empty;
}
protected override bool AreEqual(object other)
{
return other is LocalizableStringWithArguments otherResourceString &&
_messageFormat.Equals(otherResourceString._messageFormat) &&
_formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b);
}
protected override int GetHash()
{
return Hash.Combine(
_messageFormat.GetHashCode(),
Hash.CombineValues(_formatArguments));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class DiagnosticHelper
{
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
LocalizableString message;
if (messageArgs == null || messageArgs.Length == 0)
{
message = descriptor.MessageFormat;
}
else
{
message = new LocalizableStringWithArguments(descriptor.MessageFormat, messageArgs);
}
return CreateWithMessage(descriptor, location, effectiveSeverity, additionalLocations, properties, message);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
ImmutableDictionary<string, string>.Empty,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
properties,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// </param>
/// <param name="tagIndices">
/// a map of location tag to index in additional locations.
/// "AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer" for an example of usage.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
private static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
IDictionary<string, IEnumerable<int>> tagIndices,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
Contract.ThrowIfTrue(additionalLocations.IsEmpty());
Contract.ThrowIfTrue(tagIndices.IsEmpty());
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.AddRange(tagIndices.Select(kvp => new KeyValuePair<string, string>(kvp.Key, EncodeIndices(kvp.Value, additionalLocations.Count()))));
return Create(descriptor, location, effectiveSeverity, additionalLocations, properties, messageArgs);
static string EncodeIndices(IEnumerable<int> indices, int additionalLocationsLength)
{
// Ensure that the provided tag index is a valid index into additional locations.
Contract.ThrowIfFalse(indices.All(idx => idx >= 0 && idx < additionalLocationsLength));
using var stream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>));
serializer.WriteObject(stream, indices);
var jsonBytes = stream.ToArray();
stream.Close();
return Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
}
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="message">Localizable message for the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithMessage(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
LocalizableString message)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
return Diagnostic.Create(
descriptor.Id,
descriptor.Category,
message,
effectiveSeverity.ToDiagnosticSeverity() ?? descriptor.DefaultSeverity,
descriptor.DefaultSeverity,
descriptor.IsEnabledByDefault,
warningLevel: effectiveSeverity.WithDefaultSeverity(descriptor.DefaultSeverity) == ReportDiagnostic.Error ? 0 : 1,
effectiveSeverity == ReportDiagnostic.Suppress,
descriptor.Title,
descriptor.Description,
descriptor.HelpLinkUri,
location,
additionalLocations,
descriptor.CustomTags,
properties);
}
public static string GetHelpLinkForDiagnosticId(string id)
{
if (id == "RE0001")
{
// TODO: Add documentation for Regex analyzer
// Tracked with https://github.com/dotnet/roslyn/issues/48530
return null;
}
Debug.Assert(id.StartsWith("IDE", StringComparison.Ordinal));
return $"https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/{id.ToLowerInvariant()}";
}
public sealed class LocalizableStringWithArguments : LocalizableString, IObjectWritable
{
private readonly LocalizableString _messageFormat;
private readonly string[] _formatArguments;
static LocalizableStringWithArguments()
=> ObjectBinder.RegisterTypeReader(typeof(LocalizableStringWithArguments), reader => new LocalizableStringWithArguments(reader));
public LocalizableStringWithArguments(LocalizableString messageFormat, params object[] formatArguments)
{
if (messageFormat == null)
{
throw new ArgumentNullException(nameof(messageFormat));
}
if (formatArguments == null)
{
throw new ArgumentNullException(nameof(formatArguments));
}
_messageFormat = messageFormat;
_formatArguments = new string[formatArguments.Length];
for (var i = 0; i < formatArguments.Length; i++)
{
_formatArguments[i] = $"{formatArguments[i]}";
}
}
private LocalizableStringWithArguments(ObjectReader reader)
{
_messageFormat = (LocalizableString)reader.ReadValue();
var length = reader.ReadInt32();
if (length == 0)
{
_formatArguments = Array.Empty<string>();
}
else
{
using var argumentsBuilderDisposer = ArrayBuilder<string>.GetInstance(length, out var argumentsBuilder);
for (var i = 0; i < length; i++)
{
argumentsBuilder.Add(reader.ReadString());
}
_formatArguments = argumentsBuilder.ToArray();
}
}
bool IObjectWritable.ShouldReuseInSerialization => false;
void IObjectWritable.WriteTo(ObjectWriter writer)
{
writer.WriteValue(_messageFormat);
var length = _formatArguments.Length;
writer.WriteInt32(length);
for (var i = 0; i < length; i++)
{
writer.WriteString(_formatArguments[i]);
}
}
protected override string GetText(IFormatProvider formatProvider)
{
var messageFormat = _messageFormat.ToString(formatProvider);
return messageFormat != null ?
(_formatArguments.Length > 0 ? string.Format(formatProvider, messageFormat, _formatArguments) : messageFormat) :
string.Empty;
}
protected override bool AreEqual(object other)
{
return other is LocalizableStringWithArguments otherResourceString &&
_messageFormat.Equals(otherResourceString._messageFormat) &&
_formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b);
}
protected override int GetHash()
{
return Hash.Combine(
_messageFormat.GetHashCode(),
Hash.CombineValues(_formatArguments));
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class GetExtendedSemanticInfoTests
<Fact()>
Public Sub Query1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6, VisualBasicSyntaxNode)))
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6.Parent, CollectionRangeVariableSyntax)))
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(node6.Parent))
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim lambda As Action =
Sub()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
End Sub
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
Sub Main(args As String())
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query4()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function Take(x As Integer) As QueryAble
Return Me
End Function
Public Function Skip(x As Integer) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim lambda1 As Func(Of Object) =
Function() From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function() s > 1, Func(Of Boolean)).Invoke() 'BIND1:"s"
Dim lambda2 As Func(Of Object) =
Function() From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
Dim q2 As Object = From s In q Where CByte(s) 'BIND9:"Where CByte(s)"
Dim q3 As Object = From s In q Take While s > 0 'BIND10:"Take While s > 0"
Dim q4 As Object = From s In q Skip While s > 0 'BIND11:"Skip While s > 0"
Dim q5 As Object = From s In q Take 1 'BIND12:"Take 1"
Dim q6 As Object = From s In q Skip 1 'BIND13:"Skip 1"
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node9 As WhereClauseSyntax = CompilationUtils.FindBindingText(Of WhereClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo = semanticModel2.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble.Where(x As System.Func(Of System.Int32, System.Byte)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node10 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 10)
symbolInfo = semanticModel2.GetSymbolInfo(node10)
Assert.Equal("Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node11 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel2.GetSymbolInfo(node11)
Assert.Equal("Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node12 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel2.GetSymbolInfo(node12)
Assert.Equal("Function QueryAble.Take(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node13 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 13)
symbolInfo = semanticModel2.GetSymbolInfo(node13)
Assert.Equal("Function QueryAble.Skip(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Query5()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Where s > 0 'BIND:"s > 0"
End Sub
End Module
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb")
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.NarrowingBoolean, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function System.Int32.op_GreaterThan(left As System.Int32, right As System.Int32) As System.Boolean",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Select1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function Join(inner As QueryAble, outer As Func(Of Integer, Integer), inner As Func(Of Integer, Integer), x as Func(Of Integer, Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Distinct() As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND2:"s"
Select x = s+1 'BIND1:"s"
Select y = x 'BIND3:"y = x"
Where y > 0 'BIND4:"y"
Select y 'BIND5:"y"
Where y > 0 'BIND6:"y"
Select y = y 'BIND7:"y = y"
Where y > 0 'BIND8:"y"
Select y + 1 'BIND9:"y + 1"
Select z = 1 'BIND10:"z"
q1 = From s In q Select s 'BIND11:"Select s"
q1 = From s In q Select CStr(s) 'BIND12:"Select CStr(s)"
q1 = From s In q Take 1 Select s + 1 'BIND13:"Select s + 1"
q1 = From s1 In q, s2 In q Select s1 + s2 'BIND14:"Select s1 + s2"
q1 = From s1 In q Join s2 In q On s1 Equals s2 'BIND15:"Join s2 In q On s1 Equals s2"
Select s1 + s2 'BIND16:"Select s1 + s2"
q1 = From s In q Distinct 'BIND17:"Distinct"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node2))
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int32", y1.Type.ToTestDisplayString())
Dim symbolInfo As SymbolInfo
symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node5_1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5_1, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node5_2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
Dim y2 = DirectCast(semanticModel.GetDeclaredSymbol(node5_2), RangeVariableSymbol)
Assert.Equal("y", y2.Name)
Assert.Equal("System.Int32", y2.Type.ToTestDisplayString())
Assert.NotSame(y1, y2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Same(y2, semanticInfo.Symbol)
Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7)
Dim y3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("y", y3.Name)
Assert.Equal("System.Int32", y3.Type.ToTestDisplayString())
Assert.NotSame(y1, y3)
Assert.NotSame(y2, y3)
Assert.Same(y3, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode)))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Expression)
Assert.Same(y2, semanticInfo.Symbol)
Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Same(y3, semanticInfo.Symbol)
Dim node9 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 9)
Assert.Null(semanticModel.GetDeclaredSymbol(node9))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node9.Expression)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node10 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10)
Dim z = DirectCast(semanticModel.GetDeclaredSymbol(node10), RangeVariableSymbol)
Assert.Equal("z", z.Name)
Assert.Equal("System.Int32", z.Type.ToTestDisplayString())
Assert.Same(z, semanticModel.GetDeclaredSymbol(DirectCast(node10, VisualBasicSyntaxNode)))
Dim commonSymbolInfo As SymbolInfo
Dim node11 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel.GetSymbolInfo(node11)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node11, SyntaxNode))
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node12 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel.GetSymbolInfo(node12)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason)
Assert.Equal(1, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Dim node13 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 13)
symbolInfo = semanticModel.GetSymbolInfo(node13)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node14 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 14)
symbolInfo = semanticModel.GetSymbolInfo(node14)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node15 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 15)
symbolInfo = semanticModel.GetSymbolInfo(node15)
Assert.Equal("Function QueryAble.Join(inner As QueryAble, outer As System.Func(Of System.Int32, System.Int32), inner As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node16 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 16)
symbolInfo = semanticModel.GetSymbolInfo(node16)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node17 As DistinctClauseSyntax = CompilationUtils.FindBindingText(Of DistinctClauseSyntax)(compilation, "a.vb", 17)
symbolInfo = semanticModel.GetSymbolInfo(node17)
Assert.Equal("Function QueryAble.Distinct() As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub ImplicitSelect1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Integer In q Where s > 1 'BIND2:"q"
System.Console.WriteLine("------")
Dim q2 As Object = From s As Long In q Where s > 1 'BIND1:"q"
System.Console.WriteLine("------")
Dim q3 As Object = From s In q 'BIND3:"From s In q"
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, LocalSymbol)
Assert.Equal("q", s1.Name)
Assert.Equal("QueryAble", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(s1, semanticInfo.Symbol)
Dim node3 As QueryExpressionSyntax = CompilationUtils.FindBindingText(Of QueryExpressionSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node3, ExpressionSyntax))
Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind)
Assert.Null(semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub OrderBy1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x, 'BIND1:"x"
x+1, 'BIND2:"x"
x Descending 'BIND3:"x"
Order By x Descending 'BIND4:"x"
Select x 'BIND5:"x"
Dim q2 As Object = From x In q
Order By x 'BIND6:"Order By x"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
For i As Integer = 2 To 5
Dim node2to5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2to5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Next
Dim node6 As OrderByClauseSyntax = CompilationUtils.FindBindingText(Of OrderByClauseSyntax)(compilation, "a.vb", 6)
Dim symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim orderBy = DirectCast(node1.Parent.Parent, OrderByClauseSyntax)
For Each ordering In orderBy.Orderings
symbolInfo = semanticModel.GetSymbolInfo(ordering)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(ordering)
Assert.Null(commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Next
End Sub
<Fact()>
Public Sub OrderBy2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x, 'BIND1:"x"
x+1 'BIND2:"x+1"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal("Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node1)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node2 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 2)
symbolInfo = semanticModel.GetSymbolInfo(node2)
Assert.Equal("Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node2)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Select2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Select x = s, 'BIND1:"s"
y = s, 'BIND2:"s"
z = s, 'BIND3:"z = s"
w = s, 'BIND4:"w"
s, 'BIND5:"s"
z = s 'BIND6:"z = s"
Where z > 0 'BIND7:"z"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.Same(s1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)).Symbol)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim z1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("z", z1.Name)
Assert.Equal("System.Int32", z1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
Dim z2 = DirectCast(semanticModel.GetDeclaredSymbol(node6), RangeVariableSymbol)
Assert.Equal("z", z2.Name)
Assert.Equal("System.Int32", z2.Type.ToTestDisplayString())
Assert.NotSame(z1, z2)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
Assert.Same(z1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)).Symbol)
End Sub
<Fact()>
Public Sub Let1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Let x = s, 'BIND1:"s"
y = x+1, 'BIND2:"x"
x = s, 'BIND3:"x = s"
w = x 'BIND4:"x"
Dim q2 As Object = From s In q
Let x = s 'BIND5:"Let x = s"
q2 = From s In q, s2 In q
Let x = s 'BIND6:"x = s"
q2 = From s In q Join s2 In q On s Equals s2
Let x = s 'BIND7:"x = s"
q2 = From s In q Select s+1
Let x = 1 'BIND8:"x = 1"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason)
Assert.Equal(1, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Dim node5 As LetClauseSyntax = CompilationUtils.FindBindingText(Of LetClauseSyntax)(compilation, "a.vb", 5)
symbolInfo = semanticModel.GetSymbolInfo(node5)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node6)
Assert.Null(commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7)
symbolInfo = semanticModel.GetSymbolInfo(node7)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node8 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 8)
symbolInfo = semanticModel.GetSymbolInfo(node8)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node8)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Let2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s In qi
Let x = s, 'BIND1:"x = s"
y = x+1, 'BIND2:"y = x+1"
x = s 'BIND3:"x = s"
Dim q2 As Object = From s In qi Join s2 In qi On s Equals s2 'BIND7:"Join s2 In qi On s Equals s2"
Let x = s, 'BIND4:"x = s"
y = x+1, 'BIND5:"y = x+1"
x = s 'BIND6:"x = s"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)(x As System.Func(Of System.Int32, <anonymous type: Key s As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 2)
symbolInfo = semanticModel.GetSymbolInfo(node2)
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node4 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 4)
symbolInfo = semanticModel.GetSymbolInfo(node4)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
symbolInfo = semanticModel.GetSymbolInfo(node5)
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node7 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 7)
symbolInfo = semanticModel.GetSymbolInfo(node7)
Assert.Equal("Function QueryAble(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)(inner As QueryAble(Of System.Int32), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As Integer)
Dim xxx = From i In New Integer() {1, 2, x.ToString().Length } Select y = x 'BIND1:"x.ToString"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery2">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As String)
Dim xxx = From i In New Integer() {1, 2, x.Length } Select y = x 'BIND1:"x.Length"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery3">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As Integer)
Dim xxx = From i In New Integer() {1, 2 } Select y = x.ToString.Length 'BIND1:"x.ToString"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery4()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery4">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As String)
Dim xxx = From i In New Integer() {1, 2 } Select y = x.Length.ToString() 'BIND1:"x.Length"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub From1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Class QueryAble2(Of T)
Public Function AsQueryable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Class QueryAble3(Of T)
Public Function AsEnumerable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Class QueryAble4(Of T)
Inherits QueryAble(Of T)
End Class
Class QueryAble5
Public Function Cast(Of T)() As QueryAble4(Of T)
Return New QueryAble4(Of T)()
End Function
End Class
Public Function AsEnumerable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Module Program
Function Test(Of T)(x As T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s In qi
From x In s, 'BIND1:"s"
y In Test(x), 'BIND2:"x"
x In s, 'BIND3:"x In s"
w In x 'BIND4:"x"
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q2 As Object = From s1 In qb, s2 In qs
Select s1+s2 'BIND5:"s2"
Dim q3 As Object = From s1 In qb, s2 In qs
Select s1+s2 'BIND6:"s1+s2"
Dim q4 As Object = From s1 In qb, s2 In qs
Select s3 = s1+s2 'BIND7:"s3"
Dim q5 As Object = From s1 In qb, s2 In qs
Let s3 = 'BIND8:"s3"
CInt(s1+s2) 'BIND9:"s1"
Dim q6 As Object = From s In qi 'BIND10:"From s In qi"
From x In s 'BIND11:"From x In s"
Dim q6 As Object = From s In qi 'BIND12:"From s In qi"
Dim q As Object
q = From s In qi 'BIND13:"s In qi"
q = From s In qi, s2 In s 'BIND14:"s2 In s"
q = From s In qi, s2 In s, s5 As Integer In s2 'BIND15:"s5 As Integer In s2"
Dim qii As New QueryAble(Of Integer)(0)
q = From s3 As Integer In qii 'BIND16:"s3 As Integer In qii"
q = From s4 As Long In qii 'BIND17:"s4 As Long In qii"
q = From s In qi, s2 In s From s6 As Long In s2 'BIND18:"s6 As Long In s2"
Dim qj As New QueryAble2(Of Integer)()
q = From s7 In qj 'BIND19:"s7 In qj"
Dim qjj As New QueryAble(Of QueryAble2(Of Integer))(0)
q = From s in qjj, s8 In s 'BIND20:"s8 In s"
q = From s9 As Integer In New QueryAble3(Of Integer)() 'BIND21:"s9 As Integer In New QueryAble3(Of Integer)()"
q = From s10 As Long In qj 'BIND22:"s10 As Long In qj"
q = From s in qjj, s11 As Integer In s 'BIND23:"s11 As Integer In s"
q = From s in qjj, s12 As Long In s 'BIND24:"s12 As Long In s"
q = From s In qi, s2 In s, s13 In s2 'BIND25:"s13 In s2"
Select s13
q = From s In qi, s2 In s, s14 In s2 'BIND26:"s14 In s2"
Let s15 = 0
q = From s16 In New QueryAble5() 'BIND27:"s16 In New QueryAble5()"
Take 10
End Sub
<System.Runtime.CompilerServices.Extension()>
Public Function Take(Of T)(this As QueryAble(Of T), x as Integer) As QueryAble(Of T)
Return this
End Function
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax).Identifier))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node3 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, CollectionRangeVariableSyntax).Identifier))
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s2", s2.Name)
Assert.Equal("System.Int16", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
Assert.Null(semanticModel.GetDeclaredSymbol(node6))
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("s3", s3.Name)
Assert.Equal("System.Int16", s3.Type.ToTestDisplayString())
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
s3 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol)
Assert.Equal("s3", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Dim node9 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 9)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node9, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s1", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node10 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 10)
Dim symbolInfo = semanticModel.GetSymbolInfo(node10)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node11 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel.GetSymbolInfo(node11)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node12 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel.GetSymbolInfo(node12)
Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).Select(Of QueryAble(Of QueryAble(Of System.Int32)))(x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32)))) As QueryAble(Of QueryAble(Of QueryAble(Of System.Int32)))", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim collectionInfo As CollectionRangeVariableSymbolInfo
Dim node13 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 13)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node13)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s As QueryAble(Of QueryAble(Of System.Int32))", semanticModel.GetDeclaredSymbol(node13).ToTestDisplayString())
If True Then
Dim node14 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).SelectMany(Of QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)(m As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32))), x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s2 As QueryAble(Of System.Int32)", semanticModel.GetDeclaredSymbol(node14).ToTestDisplayString())
Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14)
End If
If True Then
Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 15)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node15)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s5 As System.Int32", semanticModel.GetDeclaredSymbol(node15).ToTestDisplayString())
End If
If True Then
Dim node16 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 16)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node16)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s3 As System.Int32", semanticModel.GetDeclaredSymbol(node16).ToTestDisplayString())
End If
If True Then
Dim node17 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 17)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node17)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s4 As System.Int64", semanticModel.GetDeclaredSymbol(node17).ToTestDisplayString())
End If
If True Then
Dim node18 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 18)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node18)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int64)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s6 As System.Int64", semanticModel.GetDeclaredSymbol(node18).ToTestDisplayString())
End If
If True Then
Dim node19 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 19)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node19)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s7 As System.Int32", semanticModel.GetDeclaredSymbol(node19).ToTestDisplayString())
End If
If True Then
Dim node20 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 20)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node20)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s8 As System.Int32", semanticModel.GetDeclaredSymbol(node20).ToTestDisplayString())
End If
If True Then
Dim node21 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 21)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node21)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble3(Of System.Int32).AsEnumerable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s9 As System.Int32", semanticModel.GetDeclaredSymbol(node21).ToTestDisplayString())
End If
If True Then
Dim node22 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 22)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node22)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s10 As System.Int64", semanticModel.GetDeclaredSymbol(node22).ToTestDisplayString())
End If
If True Then
Dim node23 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 23)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node23)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s11 As System.Int32", semanticModel.GetDeclaredSymbol(node23).ToTestDisplayString())
End If
If True Then
Dim node24 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 24)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node24)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int64)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s12 As System.Int64", semanticModel.GetDeclaredSymbol(node24).ToTestDisplayString())
End If
If True Then
Dim node25 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 25)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node25)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, System.Int32)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s13 As System.Int32", semanticModel.GetDeclaredSymbol(node25).ToTestDisplayString())
End If
If True Then
Dim node26 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 26)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node26)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s14 As System.Int32", semanticModel.GetDeclaredSymbol(node26).ToTestDisplayString())
End If
If True Then
Dim node27 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 27)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node27)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble5.Cast(Of System.Object)() As QueryAble4(Of System.Object)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s16 As System.Object", semanticModel.GetDeclaredSymbol(node27).ToTestDisplayString())
End If
End Sub
<Fact()>
Public Sub Join1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Join x In qb 'BIND1:"x"
On s Equals x + 1 'BIND2:"x"
Join y In qs 'BIND3:"y"
Join x In qu 'BIND4:"x"
On y + 1 Equals 'BIND5:"y"
x 'BIND6:"x"
On y Equals s
Join w In ql On w Equals y And w Equals x 'BIND7:"x"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.Same(x1, x2)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("x", x3.Name)
Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString())
Assert.NotSame(x1, x3)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Null(semanticInfo.Symbol)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
End Sub
<Fact()>
Public Sub GroupBy1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Join x In qb
On s Equals x
Join y In qs
Join x In qu
On y Equals
x
On y Equals s
Join w In ql On w Equals y And w Equals x
Group i1 = s+1, 'BIND1:"s"
x, 'BIND2:"x"
x 'BIND3:"x"
By k1 = y+1S, 'BIND4:"y"
w, 'BIND5:"w"
w 'BIND6:"w"
Into Group, 'BIND7:"Group"
k1= Count(), 'BIND8:"k1"
k1= Count(), 'BIND9:"k1"
r2 = Count(i1+ 'BIND10:"i1"
x) 'BIND11:"x"
Select w, 'BIND12:"w"
k1 'BIND13:"k1"
Dim q2 As Object = From s In qi Group By s Into Group 'BIND14:"Group By s Into Group"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s.Name)
Assert.Equal("System.Int32", s.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim i1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent.Parent), RangeVariableSymbol)
Assert.Equal("i1", i1.Name)
Assert.Equal("System.Int32", i1.Type.ToTestDisplayString())
Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode)))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Dim x1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2.Parent), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node2.Parent, ExpressionRangeVariableSyntax))
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim x3 = semanticModel.GetDeclaredSymbol(node3.Parent)
Assert.NotSame(x1, x3)
Assert.NotSame(x2, x3)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim y = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("y", y.Name)
Assert.Equal("System.Int16", y.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim k1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent.Parent), RangeVariableSymbol)
Assert.Equal("k1", k1.Name)
Assert.Equal("System.Int16", k1.Type.ToTestDisplayString())
Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode)))
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Dim w1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int64", w1.Type.ToTestDisplayString())
Dim w2 = DirectCast(semanticModel.GetDeclaredSymbol(node5.Parent), RangeVariableSymbol)
Assert.Equal("w", w2.Name)
Assert.Equal("System.Int64", w2.Type.ToTestDisplayString())
Assert.NotSame(w1, w2)
symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node5.Parent, ExpressionRangeVariableSyntax))
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
Dim w3 = semanticModel.GetDeclaredSymbol(node6.Parent)
Assert.NotSame(w1, w3)
Assert.NotSame(w2, w3)
Dim node7 As AggregationRangeVariableSyntax = CompilationUtils.FindBindingText(Of AggregationRangeVariableSyntax)(compilation, "a.vb", 7)
Dim gr = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("Group", gr.Name)
Assert.Equal("QueryAble(Of <anonymous type: Key i1 As System.Int32, Key x As System.Byte, Key $2080 As System.Byte>)", gr.Type.ToTestDisplayString())
Assert.Same(gr, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode)))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Aggregation)
Assert.Same(gr.Type, semanticInfo.Type)
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Same(gr.Type, semanticInfo.ConvertedType)
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Null(semanticInfo.Symbol)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Null(semanticInfo.Alias)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Dim k2 = DirectCast(semanticModel.GetDeclaredSymbol(node8.Parent.Parent), RangeVariableSymbol)
Assert.Equal("k1", k2.Name)
Assert.Equal("System.Int32", k2.Type.ToTestDisplayString())
Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode)))
Assert.Same(k2, semanticModel.GetDeclaredSymbol(node8))
Assert.NotSame(k1, k2)
Dim node9 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9)
Dim k3 = semanticModel.GetDeclaredSymbol(node9)
Assert.NotNull(k3)
Assert.NotSame(k1, k3)
Assert.NotSame(k2, k3)
Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax))
Assert.Same(i1, semanticInfo.Symbol)
Dim node11 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 11)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node11, ExpressionSyntax))
Assert.Same(x2, semanticInfo.Symbol)
Dim node12 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 12)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node12, ExpressionSyntax))
Assert.Same(w2, semanticInfo.Symbol)
Dim node13 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 13)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node13, ExpressionSyntax))
Assert.Same(k1, semanticInfo.Symbol)
Dim node14 As GroupByClauseSyntax = CompilationUtils.FindBindingText(Of GroupByClauseSyntax)(compilation, "a.vb", 14)
symbolInfo = semanticModel.GetSymbolInfo(node14)
Assert.Equal("Function QueryAble(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)(key As System.Func(Of System.Int32, System.Int32), into As System.Func(Of System.Int32, QueryAble(Of System.Int32), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub GroupJoin1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Group Join x In qb 'BIND1:"x"
On s Equals x + 1 'BIND2:"x"
Into x = Group 'BIND8:"x"
Group Join y In qs 'BIND3:"y"
Group Join x In qu 'BIND4:"x"
On y + 1 Equals 'BIND5:"y"
x 'BIND6:"x"
Into Group
On y Equals s
Into y = Group
Group Join w In ql On w Equals y And w Equals x 'BIND7:"x"
Into Group
Dim q2 As Object = From s In qi
Group Join x In qb On s Equals x Into Group 'BIND9:"Group Join x In qb On s Equals x Into Group"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.Same(x1, x2)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol)
Assert.Equal("x", x4.Name)
Assert.Equal("QueryAble(Of System.Byte)", x4.Type.ToTestDisplayString())
Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode)))
Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x4, semanticModel.GetDeclaredSymbol(node8.Parent.Parent))
Assert.NotSame(x1, x4)
Assert.NotSame(x2, x4)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("x", x3.Name)
Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString())
Assert.NotSame(x1, x3)
Assert.NotSame(x2, x3)
Assert.NotSame(x4, x3)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Same(x3, semanticInfo.Symbol)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x4, semanticInfo.Symbol)
Dim node9 As GroupJoinClauseSyntax = CompilationUtils.FindBindingText(Of GroupJoinClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo = semanticModel.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of QueryExpressionSyntax)().First()
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(1):
IInvocationOperation ( Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>).GroupJoin(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)(inner As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), outerKey As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), innerKey As System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInvocationOperation ( Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Instance Receiver:
ILocalReferenceOperation: qi (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'qi')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qb')
ILocalReferenceOperation: qb (OperationKind.LocalReference, Type: QueryAble(Of System.Byte)) (Syntax: 'qb')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Byte, System.Int32), IsImplicit) (Syntax: 'x + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Byte) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32, $VB$ItAnonymous As QueryAble(Of System.Byte)) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IInvocationOperation ( Function QueryAble(Of System.Int16).GroupJoin(Of System.UInt32, System.Int64, <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)(inner As QueryAble(Of System.UInt32), outerKey As System.Func(Of System.Int16, System.Int64), innerKey As System.Func(Of System.UInt32, System.Int64), x As System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
ILocalReferenceOperation: qs (OperationKind.LocalReference, Type: QueryAble(Of System.Int16)) (Syntax: 'qs')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qu')
ILocalReferenceOperation: qu (OperationKind.LocalReference, Type: QueryAble(Of System.UInt32)) (Syntax: 'qu')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, System.Int64), IsImplicit) (Syntax: 'y + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int16) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y + 1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'y + 1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y + 1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.UInt32, System.Int64), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.UInt32) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.UInt32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int16, $VB$ItAnonymous As QueryAble(Of System.UInt32)) As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'y In qs')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'y')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.Group As QueryAble(Of System.UInt32) (OperationKind.PropertyReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), IsImplicit) (Syntax: 'y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, $VB$ItAnonymous As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILocalReferenceOperation: ql (OperationKind.LocalReference, Type: QueryAble(Of System.Int64)) (Syntax: 'ql')
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(2):
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w')
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsInvalid) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'w')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w')
IAnonymousFunctionOperation (Symbol: Function (w As System.Int64) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(2):
IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w')
IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w')
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, $VB$ItAnonymous As ?) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(4):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
]]>.Value)
End Sub
<Fact()>
Public Sub Aggregate1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count() As Integer
End Function
End Class
Module Program
Function Test(Of T)(x as T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q1 As Object = Aggregate s In qi, 'BIND1:"s"
s In 'BIND2:"s"
Test(qb) 'BIND6:"qb"
Into x = 'BIND3:"x"
Where(s > 0), 'BIND4:"s"
x = Distinct 'BIND5:"x"
Dim q2 As Object = Aggregate s1 In New QueryAble(Of QueryAble(Of Integer))(0),
s2 In Test(s1) 'BIND7:"s1"
Into x = Distinct
q2 = DirectCast(qi.Select(Function(i) i), Object) 'BIND8:"qi.Select(Function(i) i)"
q2 = Aggregate i In qi Into [Select](i) 'BIND9:"[Select](i)"
Dim qii As New QueryAble(Of QueryAble(Of Integer))(0)
q2 = Aggregate ii In qii
Into [Select](From i In ii) 'BIND10:"ii"
q2 = Aggregate i In qi Into Count(i) 'BIND11:"Count(i)"
q2 = Aggregate i In qi Into Count() 'BIND12:"Aggregate i In qi Into Count()"
q2 = Aggregate i In qi Into Count(), [Select](i) 'BIND13:"Aggregate i In qi Into Count(), [Select](i)"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode)))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax)))
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent))
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Assert.Same(s1, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Equal("qb As QueryAble(Of System.Byte)", semanticInfo.Symbol.ToTestDisplayString())
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
For i As Integer = 8 To 9
Dim node8 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Null(semanticInfo.Alias)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Next
Dim node9 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 9)
Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node9, FunctionAggregationSyntax))
Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.Equal(0, symbolInfo2.CandidateSymbols.Length)
Dim commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node9, SyntaxNode))
Assert.Equal(symbolInfo1.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Same(symbolInfo1.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax))
Assert.Equal("ii As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
Dim node11 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 11)
symbolInfo1 = semanticModel.GetSymbolInfo(node11)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason)
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length)
Assert.Equal("Function QueryAble(Of System.Int32).Count() As System.Int32", symbolInfo1.CandidateSymbols(0).ToTestDisplayString())
symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node11, FunctionAggregationSyntax))
Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.True(symbolInfo1.CandidateSymbols.SequenceEqual(symbolInfo2.CandidateSymbols))
Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12)
symbolInfo1 = semanticModel.GetSymbolInfo(node12)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo3 As AggregateClauseSymbolInfo = semanticModel.GetAggregateClauseSymbolInfo(node12)
Assert.Null(symbolInfo3.Select1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node13 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 13)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node13)
Assert.Null(symbolInfo3.Select1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
End Sub
<Fact()>
Public Sub Aggregate2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count() As Integer
End Function
End Class
Module Program
Function Test(Of T)(x as T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q1 As Object = From y In qs
Aggregate s In qi, 'BIND1:"s"
s In qb 'BIND2:"s"
Into x = 'BIND3:"x"
Where(s > 'BIND4:"s"
y), 'BIND6:"y"
x = Distinct 'BIND5:"x"
Select x 'BIND7:"x"
Dim q2 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In Test(s1) 'BIND8:"s1"
Into x = Distinct
Dim q3 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In s1 Into Count() 'BIND9:"Aggregate s2 In s1 Into Count()"
Dim q4 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True
Aggregate s2 In s1 Into Count() 'BIND10:"Aggregate s2 In s1 Into Count()"
Dim q5 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND11:"Aggregate s2 In s1 Into Count(), [Select](s2)"
Dim q6 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True
Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND12:"Aggregate s2 In s1 Into Count(), [Select](s2)"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode)))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax)))
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent))
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Assert.Same(s1, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Dim y1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
Dim node9 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo3 As AggregateClauseSymbolInfo
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node9)
symbolInfo1 = symbolInfo3.Select1
Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node10 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 10)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node10)
symbolInfo1 = symbolInfo3.Select1
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node11 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 11)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node11)
symbolInfo1 = symbolInfo3.Select1
Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
symbolInfo1 = symbolInfo3.Select2
Assert.Equal("Function QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)(x As System.Func(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>, <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node12)
symbolInfo1 = symbolInfo3.Select1
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(True, symbolInfo1.IsEmpty)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
symbolInfo1 = symbolInfo3.Select2
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(True, symbolInfo1.IsEmpty)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Aggregate3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q0 As Object
q0 = From i In qi, b In qb
Aggregate s In qs Into Where(True) 'BIND1:"Aggregate s In qs Into Where(True)"
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Into Where(True), Distinct() 'BIND2:"Aggregate s In qs Into Where(True), Distinct()"
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Into Where(True) 'BIND3:"Aggregate s In qs Into Where(True)"
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Into Where(True), Distinct() 'BIND4:"Aggregate s In qs Into Where(True), Distinct()"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim symbolInfo As SymbolInfo
Dim aggregateInfo As AggregateClauseSymbolInfo
For i As Integer = 0 To 1
Dim node1 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 1 + 2 * i)
aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node1)
symbolInfo = aggregateInfo.Select1
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = aggregateInfo.Select2
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node2 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 2 + 2 * i)
aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node2)
symbolInfo = aggregateInfo.Select1
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = aggregateInfo.Select2
Assert.Equal("Function QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>).Select(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)(x As System.Func(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>, <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)) As QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Next
End Sub
<WorkItem(546132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546132")>
<Fact()>
Public Sub SymbolInfoForFunctionAgtAregationSyntax()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Function GroupBy(Of K, R)(ByVal key As Func(Of Integer, K), ByVal result As Func(Of K, cls1, R)) As cls1
Return Nothing
End Function
Sub aggr4(Of T)(ByVal this As T)
End Sub
End Class
Module AggrArgsInvalidmod
Sub AggrArgsInvalid()
Dim colm As New cls1
Dim q4 = From i In colm Group By vbCrLf Into aggr4(4)
End Sub
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore})
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "aggr4").WithArguments("aggr4"))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel As SemanticModel = compilation.GetSemanticModel(tree)
Dim node = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("aggr4(4)", StringComparison.Ordinal)).Parent, FunctionAggregationSyntax)
Dim info = semanticModel.GetSymbolInfo(node)
Assert.NotNull(info)
Assert.Null(info.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason)
Assert.Equal(2, info.CandidateSymbols.Length)
End Sub
<WorkItem(542521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542521")>
<Fact()>
Public Sub AddressOfOperatorInQuery()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module CodCov004mod
Function scen2() As Object
Return Nothing
End Function
Sub CodCov004()
Dim q = From a In AddressOf scen2
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim diagnostics = semanticModel.GetDiagnostics()
Assert.NotEmpty(diagnostics)
End Sub
<WorkItem(542823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542823")>
<Fact()>
Public Sub DefaultAggregateClauseInfo()
Dim aggrClauseSymInfo = New AggregateClauseSymbolInfo()
Assert.Null(aggrClauseSymInfo.Select1.Symbol)
Assert.Equal(0, aggrClauseSymInfo.Select1.CandidateSymbols.Length)
Assert.Null(aggrClauseSymInfo.Select2.Symbol)
Assert.Equal(0, aggrClauseSymInfo.Select2.CandidateSymbols.Length)
End Sub
<WorkItem(543084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543084")>
<Fact()>
Public Sub MissingIdentifierNameSyntaxInIncompleteLetClause()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim numbers = New Integer() {4, 5}
Dim q1 = From num In numbers Let n As
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("n As", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First()
Dim info = semanticModel.GetTypeInfo(node)
Assert.NotNull(info)
Assert.Equal(TypeInfo.None, info)
End Sub
<WorkItem(542914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542914")>
<Fact()>
Public Sub Bug10356()
Dim compilation = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim numbers = New Integer() {4, 5}
Dim d = From z In New Integer() {1, 2, 3}
Let
Group By
End Sub
End Module
]]></file>
</compilation>, {SystemCoreRef})
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("By", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First()
Dim containingSymbol = DirectCast(semanticModel, SemanticModel).GetEnclosingSymbol(node.SpanStart)
Assert.Equal("Function (z As System.Int32) As <anonymous type: Key z As System.Int32, Key Group As ?>", DirectCast(containingSymbol, Symbol).ToTestDisplayString())
End Sub
<WorkItem(543161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543161")>
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PartitionWhileClauseSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticSummary.ImplicitConversion.Kind)
Assert.Null(semanticSummary.Symbol)
Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason)
Assert.Equal(1, semanticSummary.CandidateSymbols.Length)
Assert.Equal("Function QueryAble(Of System.Int32).TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble(Of System.Int32)", semanticSummary.CandidateSymbols(0).ToTestDisplayString())
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
End Sub
<WorkItem(546165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546165")>
<Fact()>
Public Sub QueryInsideEnumMemberDecl()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module Test
Enum Enum1
x = (From i In New Integer() {4, 5} Where True Select 1).First 'BIND:"True"
End Enum
End Module
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Symbol)
Assert.True(semanticSummary.ConstantValue.HasValue)
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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class GetExtendedSemanticInfoTests
<Fact()>
Public Sub Query1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6, VisualBasicSyntaxNode)))
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6.Parent, CollectionRangeVariableSyntax)))
Assert.Same(s6, semanticModel1.GetDeclaredSymbol(node6.Parent))
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim lambda As Action =
Sub()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
End Sub
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function()
System.Console.WriteLine(s) 'BIND1:"s"
Return True
End Function, Func(Of Boolean)).Invoke()
Dim q2 As Object = From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
Sub Main(args As String())
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Query4()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function Take(x As Integer) As QueryAble
Return Me
End Function
Public Function Skip(x As Integer) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim lambda1 As Func(Of Object) =
Function() From s In q 'BIND6:"s"
Where s > 0 'BIND3:"s"
Where 10 > s 'BIND2:"s"
Where DirectCast(Function() s > 1, Func(Of Boolean)).Invoke() 'BIND1:"s"
Dim lambda2 As Func(Of Object) =
Function() From s In 'BIND7:"s"
(From s In q 'BIND8:"s"
Where s > 0) 'BIND5:"s"
Where 10 > s 'BIND4:"s"
Dim q2 As Object = From s In q Where CByte(s) 'BIND9:"Where CByte(s)"
Dim q3 As Object = From s In q Take While s > 0 'BIND10:"Take While s > 0"
Dim q4 As Object = From s In q Skip While s > 0 'BIND11:"Skip While s > 0"
Dim q5 As Object = From s In q Take 1 'BIND12:"Take 1"
Dim q6 As Object = From s In q Skip 1 'BIND13:"Skip 1"
End Sub
End Module
]]></file>
</compilation>)
'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
'----------------------------
Dim semanticModel1 = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node1, node2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Assert.NotEqual(node1, node3)
Assert.NotEqual(node2, node3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6)
Dim s6 = semanticModel1.GetDeclaredSymbol(node6)
Assert.Same(s1, s6)
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.NotSame(s1, s7)
Assert.Equal("s", s7.Name)
Assert.Equal("System.Int32", s7.Type.ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = semanticInfo.Symbol
Assert.Same(s7, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s4)
Assert.NotSame(s3, s4)
Assert.Equal("s", s4.Name)
Assert.Equal("System.Int32", s4.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8))
'----------------------------
Dim semanticModel2 = compilation.GetSemanticModel(tree)
Assert.NotSame(semanticModel1, semanticModel2)
Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.NotSame(s1, s2)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.NotEqual(node_3, node_2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Assert.NotEqual(node_3, node_1)
Assert.NotEqual(node_2, node_1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s2, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node9 As WhereClauseSyntax = CompilationUtils.FindBindingText(Of WhereClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo = semanticModel2.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble.Where(x As System.Func(Of System.Int32, System.Byte)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node10 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 10)
symbolInfo = semanticModel2.GetSymbolInfo(node10)
Assert.Equal("Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node11 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel2.GetSymbolInfo(node11)
Assert.Equal("Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node12 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel2.GetSymbolInfo(node12)
Assert.Equal("Function QueryAble.Take(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node13 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 13)
symbolInfo = semanticModel2.GetSymbolInfo(node13)
Assert.Equal("Function QueryAble.Skip(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Query5()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Where s > 0 'BIND:"s > 0"
End Sub
End Module
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb")
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.NarrowingBoolean, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function System.Int32.op_GreaterThan(left As System.Int32, right As System.Int32) As System.Boolean",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub Select1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
Public Function Join(inner As QueryAble, outer As Func(Of Integer, Integer), inner As Func(Of Integer, Integer), x as Func(Of Integer, Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Distinct() As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q 'BIND2:"s"
Select x = s+1 'BIND1:"s"
Select y = x 'BIND3:"y = x"
Where y > 0 'BIND4:"y"
Select y 'BIND5:"y"
Where y > 0 'BIND6:"y"
Select y = y 'BIND7:"y = y"
Where y > 0 'BIND8:"y"
Select y + 1 'BIND9:"y + 1"
Select z = 1 'BIND10:"z"
q1 = From s In q Select s 'BIND11:"Select s"
q1 = From s In q Select CStr(s) 'BIND12:"Select CStr(s)"
q1 = From s In q Take 1 Select s + 1 'BIND13:"Select s + 1"
q1 = From s1 In q, s2 In q Select s1 + s2 'BIND14:"Select s1 + s2"
q1 = From s1 In q Join s2 In q On s1 Equals s2 'BIND15:"Join s2 In q On s1 Equals s2"
Select s1 + s2 'BIND16:"Select s1 + s2"
q1 = From s In q Distinct 'BIND17:"Distinct"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node2))
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int32", y1.Type.ToTestDisplayString())
Dim symbolInfo As SymbolInfo
symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node5_1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5_1, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node5_2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
Dim y2 = DirectCast(semanticModel.GetDeclaredSymbol(node5_2), RangeVariableSymbol)
Assert.Equal("y", y2.Name)
Assert.Equal("System.Int32", y2.Type.ToTestDisplayString())
Assert.NotSame(y1, y2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Same(y2, semanticInfo.Symbol)
Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7)
Dim y3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("y", y3.Name)
Assert.Equal("System.Int32", y3.Type.ToTestDisplayString())
Assert.NotSame(y1, y3)
Assert.NotSame(y2, y3)
Assert.Same(y3, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode)))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Expression)
Assert.Same(y2, semanticInfo.Symbol)
Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Same(y3, semanticInfo.Symbol)
Dim node9 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 9)
Assert.Null(semanticModel.GetDeclaredSymbol(node9))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node9.Expression)
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node10 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10)
Dim z = DirectCast(semanticModel.GetDeclaredSymbol(node10), RangeVariableSymbol)
Assert.Equal("z", z.Name)
Assert.Equal("System.Int32", z.Type.ToTestDisplayString())
Assert.Same(z, semanticModel.GetDeclaredSymbol(DirectCast(node10, VisualBasicSyntaxNode)))
Dim commonSymbolInfo As SymbolInfo
Dim node11 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel.GetSymbolInfo(node11)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node11, SyntaxNode))
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node12 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel.GetSymbolInfo(node12)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason)
Assert.Equal(1, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Dim node13 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 13)
symbolInfo = semanticModel.GetSymbolInfo(node13)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node14 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 14)
symbolInfo = semanticModel.GetSymbolInfo(node14)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node15 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 15)
symbolInfo = semanticModel.GetSymbolInfo(node15)
Assert.Equal("Function QueryAble.Join(inner As QueryAble, outer As System.Func(Of System.Int32, System.Int32), inner As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node16 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 16)
symbolInfo = semanticModel.GetSymbolInfo(node16)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node17 As DistinctClauseSyntax = CompilationUtils.FindBindingText(Of DistinctClauseSyntax)(compilation, "a.vb", 17)
symbolInfo = semanticModel.GetSymbolInfo(node17)
Assert.Equal("Function QueryAble.Distinct() As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub ImplicitSelect1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Integer In q Where s > 1 'BIND2:"q"
System.Console.WriteLine("------")
Dim q2 As Object = From s As Long In q Where s > 1 'BIND1:"q"
System.Console.WriteLine("------")
Dim q3 As Object = From s In q 'BIND3:"From s In q"
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, LocalSymbol)
Assert.Equal("q", s1.Name)
Assert.Equal("QueryAble", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(s1, semanticInfo.Symbol)
Dim node3 As QueryExpressionSyntax = CompilationUtils.FindBindingText(Of QueryExpressionSyntax)(compilation, "a.vb", 3)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node3, ExpressionSyntax))
Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind)
Assert.Null(semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact()>
Public Sub OrderBy1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x, 'BIND1:"x"
x+1, 'BIND2:"x"
x Descending 'BIND3:"x"
Order By x Descending 'BIND4:"x"
Select x 'BIND5:"x"
Dim q2 As Object = From x In q
Order By x 'BIND6:"Order By x"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
For i As Integer = 2 To 5
Dim node2to5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2to5, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Same(s1, semanticInfo.Symbol)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Next
Dim node6 As OrderByClauseSyntax = CompilationUtils.FindBindingText(Of OrderByClauseSyntax)(compilation, "a.vb", 6)
Dim symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim orderBy = DirectCast(node1.Parent.Parent, OrderByClauseSyntax)
For Each ordering In orderBy.Orderings
symbolInfo = semanticModel.GetSymbolInfo(ordering)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(ordering)
Assert.Null(commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Next
End Sub
<Fact()>
Public Sub OrderBy2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x, 'BIND1:"x"
x+1 'BIND2:"x+1"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal("Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node1)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node2 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 2)
symbolInfo = semanticModel.GetSymbolInfo(node2)
Assert.Equal("Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node2)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Select2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Select x = s, 'BIND1:"s"
y = s, 'BIND2:"s"
z = s, 'BIND3:"z = s"
w = s, 'BIND4:"w"
s, 'BIND5:"s"
z = s 'BIND6:"z = s"
Where z > 0 'BIND7:"z"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Assert.Same(s1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)).Symbol)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim z1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("z", z1.Name)
Assert.Equal("System.Int32", z1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Int32", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
Dim z2 = DirectCast(semanticModel.GetDeclaredSymbol(node6), RangeVariableSymbol)
Assert.Equal("z", z2.Name)
Assert.Equal("System.Int32", z2.Type.ToTestDisplayString())
Assert.NotSame(z1, z2)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
Assert.Same(z1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)).Symbol)
End Sub
<Fact()>
Public Sub Let1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s In q
Let x = s, 'BIND1:"s"
y = x+1, 'BIND2:"x"
x = s, 'BIND3:"x = s"
w = x 'BIND4:"x"
Dim q2 As Object = From s In q
Let x = s 'BIND5:"Let x = s"
q2 = From s In q, s2 In q
Let x = s 'BIND6:"x = s"
q2 = From s In q Join s2 In q On s Equals s2
Let x = s 'BIND7:"x = s"
q2 = From s In q Select s+1
Let x = 1 'BIND8:"x = 1"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason)
Assert.Equal(1, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Dim node5 As LetClauseSyntax = CompilationUtils.FindBindingText(Of LetClauseSyntax)(compilation, "a.vb", 5)
symbolInfo = semanticModel.GetSymbolInfo(node5)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node6)
Assert.Null(commonSymbolInfo.Symbol)
Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7)
symbolInfo = semanticModel.GetSymbolInfo(node7)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node8 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 8)
symbolInfo = semanticModel.GetSymbolInfo(node8)
Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node8)
Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Let2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s In qi
Let x = s, 'BIND1:"x = s"
y = x+1, 'BIND2:"y = x+1"
x = s 'BIND3:"x = s"
Dim q2 As Object = From s In qi Join s2 In qi On s Equals s2 'BIND7:"Join s2 In qi On s Equals s2"
Let x = s, 'BIND4:"x = s"
y = x+1, 'BIND5:"y = x+1"
x = s 'BIND6:"x = s"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)(x As System.Func(Of System.Int32, <anonymous type: Key s As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 2)
symbolInfo = semanticModel.GetSymbolInfo(node2)
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3)
symbolInfo = semanticModel.GetSymbolInfo(node3)
Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node4 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 4)
symbolInfo = semanticModel.GetSymbolInfo(node4)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5)
symbolInfo = semanticModel.GetSymbolInfo(node5)
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
symbolInfo = semanticModel.GetSymbolInfo(node6)
Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node7 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 7)
symbolInfo = semanticModel.GetSymbolInfo(node7)
Assert.Equal("Function QueryAble(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)(inner As QueryAble(Of System.Int32), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As Integer)
Dim xxx = From i In New Integer() {1, 2, x.ToString().Length } Select y = x 'BIND1:"x.ToString"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery2">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As String)
Dim xxx = From i In New Integer() {1, 2, x.Length } Select y = x 'BIND1:"x.Length"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery3">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As Integer)
Dim xxx = From i In New Integer() {1, 2 } Select y = x.ToString.Length 'BIND1:"x.ToString"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub BindingMemberAccessInsideQuery4()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="BindingMemberAccessInsideQuery4">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(x As String)
Dim xxx = From i In New Integer() {1, 2 } Select y = x.Length.ToString() 'BIND1:"x.Length"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1)
Dim symbolInfo = model.GetSymbolInfo(node)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString())
End Sub
<Fact()>
Public Sub From1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Class QueryAble2(Of T)
Public Function AsQueryable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Class QueryAble3(Of T)
Public Function AsEnumerable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Class QueryAble4(Of T)
Inherits QueryAble(Of T)
End Class
Class QueryAble5
Public Function Cast(Of T)() As QueryAble4(Of T)
Return New QueryAble4(Of T)()
End Function
End Class
Public Function AsEnumerable As QueryAble(Of T)
Return New QueryAble(Of T)(1)
End Function
End Class
Module Program
Function Test(Of T)(x As T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s In qi
From x In s, 'BIND1:"s"
y In Test(x), 'BIND2:"x"
x In s, 'BIND3:"x In s"
w In x 'BIND4:"x"
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q2 As Object = From s1 In qb, s2 In qs
Select s1+s2 'BIND5:"s2"
Dim q3 As Object = From s1 In qb, s2 In qs
Select s1+s2 'BIND6:"s1+s2"
Dim q4 As Object = From s1 In qb, s2 In qs
Select s3 = s1+s2 'BIND7:"s3"
Dim q5 As Object = From s1 In qb, s2 In qs
Let s3 = 'BIND8:"s3"
CInt(s1+s2) 'BIND9:"s1"
Dim q6 As Object = From s In qi 'BIND10:"From s In qi"
From x In s 'BIND11:"From x In s"
Dim q6 As Object = From s In qi 'BIND12:"From s In qi"
Dim q As Object
q = From s In qi 'BIND13:"s In qi"
q = From s In qi, s2 In s 'BIND14:"s2 In s"
q = From s In qi, s2 In s, s5 As Integer In s2 'BIND15:"s5 As Integer In s2"
Dim qii As New QueryAble(Of Integer)(0)
q = From s3 As Integer In qii 'BIND16:"s3 As Integer In qii"
q = From s4 As Long In qii 'BIND17:"s4 As Long In qii"
q = From s In qi, s2 In s From s6 As Long In s2 'BIND18:"s6 As Long In s2"
Dim qj As New QueryAble2(Of Integer)()
q = From s7 In qj 'BIND19:"s7 In qj"
Dim qjj As New QueryAble(Of QueryAble2(Of Integer))(0)
q = From s in qjj, s8 In s 'BIND20:"s8 In s"
q = From s9 As Integer In New QueryAble3(Of Integer)() 'BIND21:"s9 As Integer In New QueryAble3(Of Integer)()"
q = From s10 As Long In qj 'BIND22:"s10 As Long In qj"
q = From s in qjj, s11 As Integer In s 'BIND23:"s11 As Integer In s"
q = From s in qjj, s12 As Long In s 'BIND24:"s12 As Long In s"
q = From s In qi, s2 In s, s13 In s2 'BIND25:"s13 In s2"
Select s13
q = From s In qi, s2 In s, s14 In s2 'BIND26:"s14 In s2"
Let s15 = 0
q = From s16 In New QueryAble5() 'BIND27:"s16 In New QueryAble5()"
Take 10
End Sub
<System.Runtime.CompilerServices.Extension()>
Public Function Take(Of T)(this As QueryAble(Of T), x as Integer) As QueryAble(Of T)
Return this
End Function
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", s1.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax).Identifier))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node3 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 3)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int32", w1.Type.ToTestDisplayString())
Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, CollectionRangeVariableSyntax).Identifier))
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s2", s2.Name)
Assert.Equal("System.Int16", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6)
Assert.Null(semanticModel.GetDeclaredSymbol(node6))
Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7)
Dim s3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("s3", s3.Name)
Assert.Equal("System.Int16", s3.Type.ToTestDisplayString())
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
s3 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol)
Assert.Equal("s3", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Dim node9 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 9)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node9, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s1", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node10 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 10)
Dim symbolInfo = semanticModel.GetSymbolInfo(node10)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node11 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 11)
symbolInfo = semanticModel.GetSymbolInfo(node11)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node12 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 12)
symbolInfo = semanticModel.GetSymbolInfo(node12)
Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).Select(Of QueryAble(Of QueryAble(Of System.Int32)))(x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32)))) As QueryAble(Of QueryAble(Of QueryAble(Of System.Int32)))", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim collectionInfo As CollectionRangeVariableSymbolInfo
Dim node13 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 13)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node13)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s As QueryAble(Of QueryAble(Of System.Int32))", semanticModel.GetDeclaredSymbol(node13).ToTestDisplayString())
If True Then
Dim node14 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).SelectMany(Of QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)(m As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32))), x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s2 As QueryAble(Of System.Int32)", semanticModel.GetDeclaredSymbol(node14).ToTestDisplayString())
Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14)
End If
If True Then
Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 15)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node15)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s5 As System.Int32", semanticModel.GetDeclaredSymbol(node15).ToTestDisplayString())
End If
If True Then
Dim node16 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 16)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node16)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s3 As System.Int32", semanticModel.GetDeclaredSymbol(node16).ToTestDisplayString())
End If
If True Then
Dim node17 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 17)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node17)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s4 As System.Int64", semanticModel.GetDeclaredSymbol(node17).ToTestDisplayString())
End If
If True Then
Dim node18 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 18)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node18)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int64)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s6 As System.Int64", semanticModel.GetDeclaredSymbol(node18).ToTestDisplayString())
End If
If True Then
Dim node19 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 19)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node19)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s7 As System.Int32", semanticModel.GetDeclaredSymbol(node19).ToTestDisplayString())
End If
If True Then
Dim node20 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 20)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node20)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s8 As System.Int32", semanticModel.GetDeclaredSymbol(node20).ToTestDisplayString())
End If
If True Then
Dim node21 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 21)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node21)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble3(Of System.Int32).AsEnumerable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s9 As System.Int32", semanticModel.GetDeclaredSymbol(node21).ToTestDisplayString())
End If
If True Then
Dim node22 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 22)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node22)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s10 As System.Int64", semanticModel.GetDeclaredSymbol(node22).ToTestDisplayString())
End If
If True Then
Dim node23 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 23)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node23)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s11 As System.Int32", semanticModel.GetDeclaredSymbol(node23).ToTestDisplayString())
End If
If True Then
Dim node24 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 24)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node24)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.AsClauseConversion
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int64)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s12 As System.Int64", semanticModel.GetDeclaredSymbol(node24).ToTestDisplayString())
End If
If True Then
Dim node25 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 25)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node25)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, System.Int32)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s13 As System.Int32", semanticModel.GetDeclaredSymbol(node25).ToTestDisplayString())
End If
If True Then
Dim node26 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 26)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node26)
Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
symbolInfo = collectionInfo.SelectMany
Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("s14 As System.Int32", semanticModel.GetDeclaredSymbol(node26).ToTestDisplayString())
End If
If True Then
Dim node27 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 27)
collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node27)
symbolInfo = collectionInfo.ToQueryableCollectionConversion
Assert.Equal("Function QueryAble5.Cast(Of System.Object)() As QueryAble4(Of System.Object)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason)
Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason)
Assert.Equal("s16 As System.Object", semanticModel.GetDeclaredSymbol(node27).ToTestDisplayString())
End If
End Sub
<Fact()>
Public Sub Join1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Join x In qb 'BIND1:"x"
On s Equals x + 1 'BIND2:"x"
Join y In qs 'BIND3:"y"
Join x In qu 'BIND4:"x"
On y + 1 Equals 'BIND5:"y"
x 'BIND6:"x"
On y Equals s
Join w In ql On w Equals y And w Equals x 'BIND7:"x"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.Same(x1, x2)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("x", x3.Name)
Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString())
Assert.NotSame(x1, x3)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Null(semanticInfo.Symbol)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
End Sub
<Fact()>
Public Sub GroupBy1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Join x In qb
On s Equals x
Join y In qs
Join x In qu
On y Equals
x
On y Equals s
Join w In ql On w Equals y And w Equals x
Group i1 = s+1, 'BIND1:"s"
x, 'BIND2:"x"
x 'BIND3:"x"
By k1 = y+1S, 'BIND4:"y"
w, 'BIND5:"w"
w 'BIND6:"w"
Into Group, 'BIND7:"Group"
k1= Count(), 'BIND8:"k1"
k1= Count(), 'BIND9:"k1"
r2 = Count(i1+ 'BIND10:"i1"
x) 'BIND11:"x"
Select w, 'BIND12:"w"
k1 'BIND13:"k1"
Dim q2 As Object = From s In qi Group By s Into Group 'BIND14:"Group By s Into Group"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s.Name)
Assert.Equal("System.Int32", s.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim i1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent.Parent), RangeVariableSymbol)
Assert.Equal("i1", i1.Name)
Assert.Equal("System.Int32", i1.Type.ToTestDisplayString())
Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode)))
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Dim x1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2.Parent), RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node2.Parent, ExpressionRangeVariableSyntax))
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim x3 = semanticModel.GetDeclaredSymbol(node3.Parent)
Assert.NotSame(x1, x3)
Assert.NotSame(x2, x3)
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim y = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("y", y.Name)
Assert.Equal("System.Int16", y.Type.ToTestDisplayString())
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim k1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent.Parent), RangeVariableSymbol)
Assert.Equal("k1", k1.Name)
Assert.Equal("System.Int16", k1.Type.ToTestDisplayString())
Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier))
Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode)))
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Dim w1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("w", w1.Name)
Assert.Equal("System.Int64", w1.Type.ToTestDisplayString())
Dim w2 = DirectCast(semanticModel.GetDeclaredSymbol(node5.Parent), RangeVariableSymbol)
Assert.Equal("w", w2.Name)
Assert.Equal("System.Int64", w2.Type.ToTestDisplayString())
Assert.NotSame(w1, w2)
symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node5.Parent, ExpressionRangeVariableSyntax))
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
Dim w3 = semanticModel.GetDeclaredSymbol(node6.Parent)
Assert.NotSame(w1, w3)
Assert.NotSame(w2, w3)
Dim node7 As AggregationRangeVariableSyntax = CompilationUtils.FindBindingText(Of AggregationRangeVariableSyntax)(compilation, "a.vb", 7)
Dim gr = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol)
Assert.Equal("Group", gr.Name)
Assert.Equal("QueryAble(Of <anonymous type: Key i1 As System.Int32, Key x As System.Byte, Key $2080 As System.Byte>)", gr.Type.ToTestDisplayString())
Assert.Same(gr, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode)))
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Aggregation)
Assert.Same(gr.Type, semanticInfo.Type)
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Same(gr.Type, semanticInfo.ConvertedType)
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Null(semanticInfo.Symbol)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Null(semanticInfo.Alias)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Dim k2 = DirectCast(semanticModel.GetDeclaredSymbol(node8.Parent.Parent), RangeVariableSymbol)
Assert.Equal("k1", k2.Name)
Assert.Equal("System.Int32", k2.Type.ToTestDisplayString())
Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode)))
Assert.Same(k2, semanticModel.GetDeclaredSymbol(node8))
Assert.NotSame(k1, k2)
Dim node9 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9)
Dim k3 = semanticModel.GetDeclaredSymbol(node9)
Assert.NotNull(k3)
Assert.NotSame(k1, k3)
Assert.NotSame(k2, k3)
Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax))
Assert.Same(i1, semanticInfo.Symbol)
Dim node11 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 11)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node11, ExpressionSyntax))
Assert.Same(x2, semanticInfo.Symbol)
Dim node12 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 12)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node12, ExpressionSyntax))
Assert.Same(w2, semanticInfo.Symbol)
Dim node13 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 13)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node13, ExpressionSyntax))
Assert.Same(k1, semanticInfo.Symbol)
Dim node14 As GroupByClauseSyntax = CompilationUtils.FindBindingText(Of GroupByClauseSyntax)(compilation, "a.vb", 14)
symbolInfo = semanticModel.GetSymbolInfo(node14)
Assert.Equal("Function QueryAble(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)(key As System.Func(Of System.Int32, System.Int32), into As System.Func(Of System.Int32, QueryAble(Of System.Int32), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
End Sub
<Fact()>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub GroupJoin1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Program
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s In qi
Group Join x In qb 'BIND1:"x"
On s Equals x + 1 'BIND2:"x"
Into x = Group 'BIND8:"x"
Group Join y In qs 'BIND3:"y"
Group Join x In qu 'BIND4:"x"
On y + 1 Equals 'BIND5:"y"
x 'BIND6:"x"
Into Group
On y Equals s
Into y = Group
Group Join w In ql On w Equals y And w Equals x 'BIND7:"x"
Into Group
Dim q2 As Object = From s In qi
Group Join x In qb On s Equals x Into Group 'BIND9:"Group Join x In qb On s Equals x Into Group"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("System.Byte", x1.Type.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax))
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind)
Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("x", x2.Name)
Assert.Equal("System.Byte", x2.Type.ToTestDisplayString())
Assert.Same(x1, x2)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8)
Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol)
Assert.Equal("x", x4.Name)
Assert.Equal("QueryAble(Of System.Byte)", x4.Type.ToTestDisplayString())
Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode)))
Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x4, semanticModel.GetDeclaredSymbol(node8.Parent.Parent))
Assert.NotSame(x1, x4)
Assert.NotSame(x2, x4)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4)
Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol)
Assert.Equal("x", x3.Name)
Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString())
Assert.NotSame(x1, x3)
Assert.NotSame(x2, x3)
Assert.NotSame(x4, x3)
Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax))
Assert.Same(y1, semanticInfo.Symbol)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Same(x3, semanticInfo.Symbol)
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x4, semanticInfo.Symbol)
Dim node9 As GroupJoinClauseSyntax = CompilationUtils.FindBindingText(Of GroupJoinClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo = semanticModel.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node = tree.GetRoot().DescendantNodes().OfType(Of QueryExpressionSyntax)().First()
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(1):
IInvocationOperation ( Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>).GroupJoin(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)(inner As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), outerKey As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), innerKey As System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInvocationOperation ( Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Instance Receiver:
ILocalReferenceOperation: qi (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'qi')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qb')
ILocalReferenceOperation: qb (OperationKind.LocalReference, Type: QueryAble(Of System.Byte)) (Syntax: 'qb')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Byte, System.Int32), IsImplicit) (Syntax: 'x + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Byte) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32, $VB$ItAnonymous As QueryAble(Of System.Byte)) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IInvocationOperation ( Function QueryAble(Of System.Int16).GroupJoin(Of System.UInt32, System.Int64, <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)(inner As QueryAble(Of System.UInt32), outerKey As System.Func(Of System.Int16, System.Int64), innerKey As System.Func(Of System.UInt32, System.Int64), x As System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
ILocalReferenceOperation: qs (OperationKind.LocalReference, Type: QueryAble(Of System.Int16)) (Syntax: 'qs')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qu')
ILocalReferenceOperation: qu (OperationKind.LocalReference, Type: QueryAble(Of System.UInt32)) (Syntax: 'qu')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, System.Int64), IsImplicit) (Syntax: 'y + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int16) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y + 1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'y + 1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y + 1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.UInt32, System.Int64), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.UInt32) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.UInt32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int16, $VB$ItAnonymous As QueryAble(Of System.UInt32)) As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'y In qs')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'y')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.Group As QueryAble(Of System.UInt32) (OperationKind.PropertyReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), IsImplicit) (Syntax: 'y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 's')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, $VB$ItAnonymous As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILocalReferenceOperation: ql (OperationKind.LocalReference, Type: QueryAble(Of System.Int64)) (Syntax: 'ql')
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'w')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(2):
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w')
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsInvalid) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'w')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w')
IAnonymousFunctionOperation (Symbol: Function (w As System.Int64) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'y')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(2):
IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w')
IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w')
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, $VB$ItAnonymous As ?) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(4):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
]]>.Value)
End Sub
<Fact()>
Public Sub Aggregate1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count() As Integer
End Function
End Class
Module Program
Function Test(Of T)(x as T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q1 As Object = Aggregate s In qi, 'BIND1:"s"
s In 'BIND2:"s"
Test(qb) 'BIND6:"qb"
Into x = 'BIND3:"x"
Where(s > 0), 'BIND4:"s"
x = Distinct 'BIND5:"x"
Dim q2 As Object = Aggregate s1 In New QueryAble(Of QueryAble(Of Integer))(0),
s2 In Test(s1) 'BIND7:"s1"
Into x = Distinct
q2 = DirectCast(qi.Select(Function(i) i), Object) 'BIND8:"qi.Select(Function(i) i)"
q2 = Aggregate i In qi Into [Select](i) 'BIND9:"[Select](i)"
Dim qii As New QueryAble(Of QueryAble(Of Integer))(0)
q2 = Aggregate ii In qii
Into [Select](From i In ii) 'BIND10:"ii"
q2 = Aggregate i In qi Into Count(i) 'BIND11:"Count(i)"
q2 = Aggregate i In qi Into Count() 'BIND12:"Aggregate i In qi Into Count()"
q2 = Aggregate i In qi Into Count(), [Select](i) 'BIND13:"Aggregate i In qi Into Count(), [Select](i)"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode)))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax)))
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent))
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Assert.Same(s1, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Assert.Equal("qb As QueryAble(Of System.Byte)", semanticInfo.Symbol.ToTestDisplayString())
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
For i As Integer = 8 To 9
Dim node8 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind)
Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)",
semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Null(semanticInfo.Alias)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Next
Dim node9 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 9)
Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9)
Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node9, FunctionAggregationSyntax))
Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.Equal(0, symbolInfo2.CandidateSymbols.Length)
Dim commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node9, SyntaxNode))
Assert.Equal(symbolInfo1.CandidateReason, commonSymbolInfo.CandidateReason)
Assert.Same(symbolInfo1.Symbol, commonSymbolInfo.Symbol)
Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length)
Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax))
Assert.Equal("ii As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
Dim node11 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 11)
symbolInfo1 = semanticModel.GetSymbolInfo(node11)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason)
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length)
Assert.Equal("Function QueryAble(Of System.Int32).Count() As System.Int32", symbolInfo1.CandidateSymbols(0).ToTestDisplayString())
symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node11, FunctionAggregationSyntax))
Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.True(symbolInfo1.CandidateSymbols.SequenceEqual(symbolInfo2.CandidateSymbols))
Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12)
symbolInfo1 = semanticModel.GetSymbolInfo(node12)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo3 As AggregateClauseSymbolInfo = semanticModel.GetAggregateClauseSymbolInfo(node12)
Assert.Null(symbolInfo3.Select1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node13 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 13)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node13)
Assert.Null(symbolInfo3.Select1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
End Sub
<Fact()>
Public Sub Aggregate2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count() As Integer
End Function
End Class
Module Program
Function Test(Of T)(x as T) As T
return x
End Function
Sub Main(args As String())
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q1 As Object = From y In qs
Aggregate s In qi, 'BIND1:"s"
s In qb 'BIND2:"s"
Into x = 'BIND3:"x"
Where(s > 'BIND4:"s"
y), 'BIND6:"y"
x = Distinct 'BIND5:"x"
Select x 'BIND7:"x"
Dim q2 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In Test(s1) 'BIND8:"s1"
Into x = Distinct
Dim q3 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In s1 Into Count() 'BIND9:"Aggregate s2 In s1 Into Count()"
Dim q4 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True
Aggregate s2 In s1 Into Count() 'BIND10:"Aggregate s2 In s1 Into Count()"
Dim q5 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0)
Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND11:"Aggregate s2 In s1 Into Count(), [Select](s2)"
Dim q6 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True
Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND12:"Aggregate s2 In s1 Into Count(), [Select](s2)"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1)
Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol)
Assert.Equal("s", s1.Name)
Assert.Equal("System.Int32", s1.Type.ToTestDisplayString())
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode)))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent))
Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax)))
Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2)
Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol)
Assert.Equal("s", s2.Name)
Assert.Equal("System.Byte", s2.Type.ToTestDisplayString())
Assert.NotSame(s1, s2)
Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3)
Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax)))
Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent))
Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax))
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("s", s3.Name)
Assert.Equal("System.Int32", s3.Type.ToTestDisplayString())
Assert.Same(s1, s3)
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5)
Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol)
Assert.Equal("x", x1.Name)
Assert.Equal("?", x1.Type.ToTestDisplayString())
Assert.NotSame(x1, x2)
Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax))
Dim y1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol)
Assert.Equal("y", y1.Name)
Assert.Equal("System.Int16", y1.Type.ToTestDisplayString())
Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax))
Assert.Same(x1, semanticInfo.Symbol)
Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax))
Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString())
Dim node9 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 9)
Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9)
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim symbolInfo3 As AggregateClauseSymbolInfo
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node9)
symbolInfo1 = symbolInfo3.Select1
Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node10 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 10)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node10)
symbolInfo1 = symbolInfo3.Select1
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Assert.Null(symbolInfo3.Select2.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason)
Dim node11 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 11)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node11)
symbolInfo1 = symbolInfo3.Select1
Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
symbolInfo1 = symbolInfo3.Select2
Assert.Equal("Function QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)(x As System.Func(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>, <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12)
symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node12)
symbolInfo1 = symbolInfo3.Select1
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(True, symbolInfo1.IsEmpty)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
symbolInfo1 = symbolInfo3.Select2
Assert.Null(symbolInfo1.Symbol)
Assert.Equal(True, symbolInfo1.IsEmpty)
Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason)
Assert.Equal(0, symbolInfo1.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub Aggregate3()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q0 As Object
q0 = From i In qi, b In qb
Aggregate s In qs Into Where(True) 'BIND1:"Aggregate s In qs Into Where(True)"
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Into Where(True), Distinct() 'BIND2:"Aggregate s In qs Into Where(True), Distinct()"
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Into Where(True) 'BIND3:"Aggregate s In qs Into Where(True)"
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Into Where(True), Distinct() 'BIND4:"Aggregate s In qs Into Where(True), Distinct()"
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticInfo As SemanticInfoSummary = Nothing
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim symbolInfo As SymbolInfo
Dim aggregateInfo As AggregateClauseSymbolInfo
For i As Integer = 0 To 1
Dim node1 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 1 + 2 * i)
aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node1)
symbolInfo = aggregateInfo.Select1
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = aggregateInfo.Select2
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim node2 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 2 + 2 * i)
aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node2)
symbolInfo = aggregateInfo.Select1
Assert.Null(symbolInfo.Symbol)
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
symbolInfo = aggregateInfo.Select2
Assert.Equal("Function QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>).Select(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)(x As System.Func(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>, <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)) As QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Next
End Sub
<WorkItem(546132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546132")>
<Fact()>
Public Sub SymbolInfoForFunctionAgtAregationSyntax()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Function GroupBy(Of K, R)(ByVal key As Func(Of Integer, K), ByVal result As Func(Of K, cls1, R)) As cls1
Return Nothing
End Function
Sub aggr4(Of T)(ByVal this As T)
End Sub
End Class
Module AggrArgsInvalidmod
Sub AggrArgsInvalid()
Dim colm As New cls1
Dim q4 = From i In colm Group By vbCrLf Into aggr4(4)
End Sub
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore})
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "aggr4").WithArguments("aggr4"))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel As SemanticModel = compilation.GetSemanticModel(tree)
Dim node = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("aggr4(4)", StringComparison.Ordinal)).Parent, FunctionAggregationSyntax)
Dim info = semanticModel.GetSymbolInfo(node)
Assert.NotNull(info)
Assert.Null(info.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason)
Assert.Equal(2, info.CandidateSymbols.Length)
End Sub
<WorkItem(542521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542521")>
<Fact()>
Public Sub AddressOfOperatorInQuery()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module CodCov004mod
Function scen2() As Object
Return Nothing
End Function
Sub CodCov004()
Dim q = From a In AddressOf scen2
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim diagnostics = semanticModel.GetDiagnostics()
Assert.NotEmpty(diagnostics)
End Sub
<WorkItem(542823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542823")>
<Fact()>
Public Sub DefaultAggregateClauseInfo()
Dim aggrClauseSymInfo = New AggregateClauseSymbolInfo()
Assert.Null(aggrClauseSymInfo.Select1.Symbol)
Assert.Equal(0, aggrClauseSymInfo.Select1.CandidateSymbols.Length)
Assert.Null(aggrClauseSymInfo.Select2.Symbol)
Assert.Equal(0, aggrClauseSymInfo.Select2.CandidateSymbols.Length)
End Sub
<WorkItem(543084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543084")>
<Fact()>
Public Sub MissingIdentifierNameSyntaxInIncompleteLetClause()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim numbers = New Integer() {4, 5}
Dim q1 = From num In numbers Let n As
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("n As", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First()
Dim info = semanticModel.GetTypeInfo(node)
Assert.NotNull(info)
Assert.Equal(TypeInfo.None, info)
End Sub
<WorkItem(542914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542914")>
<Fact()>
Public Sub Bug10356()
Dim compilation = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim numbers = New Integer() {4, 5}
Dim d = From z In New Integer() {1, 2, 3}
Let
Group By
End Sub
End Module
]]></file>
</compilation>, {SystemCoreRef})
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("By", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First()
Dim containingSymbol = DirectCast(semanticModel, SemanticModel).GetEnclosingSymbol(node.SpanStart)
Assert.Equal("Function (z As System.Int32) As <anonymous type: Key z As System.Int32, Key Group As ?>", DirectCast(containingSymbol, Symbol).ToTestDisplayString())
End Sub
<WorkItem(543161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543161")>
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PartitionWhileClauseSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticSummary.ImplicitConversion.Kind)
Assert.Null(semanticSummary.Symbol)
Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason)
Assert.Equal(1, semanticSummary.CandidateSymbols.Length)
Assert.Equal("Function QueryAble(Of System.Int32).TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble(Of System.Int32)", semanticSummary.CandidateSymbols(0).ToTestDisplayString())
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
End Sub
<WorkItem(546165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546165")>
<Fact()>
Public Sub QueryInsideEnumMemberDecl()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module Test
Enum Enum1
x = (From i In New Integer() {4, 5} Where True Select 1).First 'BIND:"True"
End Enum
End Module
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Symbol)
Assert.True(semanticSummary.ConstantValue.HasValue)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/CSharp/Portable/Structure/CSharpStructureHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal static class CSharpStructureHelpers
{
public const string Ellipsis = "...";
public const string MultiLineCommentSuffix = "*/";
public const int MaxXmlDocCommentBannerLength = 120;
private static readonly char[] s_newLineCharacters = new char[] { '\r', '\n' };
private static int GetCollapsibleStart(SyntaxToken firstToken)
{
// If the *next* token has any leading comments, we use the end of the last one.
// If not, we check *this* token to see if it has any trailing comments and use the last one;
// otherwise, we use the end of this token.
var start = firstToken.Span.End;
var nextToken = firstToken.GetNextToken();
if (nextToken.Kind() != SyntaxKind.None && nextToken.HasLeadingTrivia)
{
var lastLeadingCommentTrivia = nextToken.LeadingTrivia.GetLastComment();
if (lastLeadingCommentTrivia != null)
{
start = lastLeadingCommentTrivia.Value.Span.End;
}
}
if (firstToken.HasTrailingTrivia)
{
var lastTrailingCommentOrWhitespaceTrivia = firstToken.TrailingTrivia.GetLastCommentOrWhitespace();
if (lastTrailingCommentOrWhitespaceTrivia != null)
{
start = lastTrailingCommentOrWhitespaceTrivia.Value.Span.End;
}
}
return start;
}
private static (int spanEnd, int hintEnd) GetCollapsibleEnd(SyntaxToken lastToken, bool compressEmptyLines)
{
// If the token has any trailing comments, we use the end of the token;
// otherwise, the behavior depends on 'compressEmptyLines':
// false: skip to the start of the first new line trivia
// true: skip to the start of the last new line trivia preceding a non-whitespace line
//
// The hint span never includes the compressed empty lines.
var trailingTrivia = lastToken.TrailingTrivia;
var nextLeadingTrivia = compressEmptyLines ? lastToken.GetNextToken(includeZeroWidth: true, includeSkipped: true).LeadingTrivia : default;
var end = lastToken.Span.End;
int? hintEnd = null;
foreach (var trivia in trailingTrivia)
{
if (!ProcessTrivia(trivia, compressEmptyLines, ref end, ref hintEnd))
return (end, hintEnd ?? end);
}
foreach (var trivia in nextLeadingTrivia)
{
if (!ProcessTrivia(trivia, compressEmptyLines, ref end, ref hintEnd))
return (end, hintEnd ?? end);
}
return (end, hintEnd ?? end);
// Return true to keep processing trivia; otherwise, false to return the current 'end'
static bool ProcessTrivia(SyntaxTrivia trivia, bool compressEmptyLines, ref int end, ref int? hintEnd)
{
if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
{
end = trivia.SpanStart;
hintEnd ??= end;
if (!compressEmptyLines)
return false;
}
else if (!trivia.IsKind(SyntaxKind.WhitespaceTrivia))
{
// We want this trivia to be visible even when the element is collapsed
return false;
}
return true;
}
}
public static SyntaxToken GetLastInlineMethodBlockToken(SyntaxNode node)
{
var lastToken = node.GetLastToken(includeZeroWidth: true);
if (lastToken.Kind() == SyntaxKind.None)
{
return default;
}
// If the next token is a semicolon, and we aren't in the initializer of a for-loop, use that token as the end.
var nextToken = lastToken.GetNextToken(includeSkipped: true);
if (nextToken.Kind() != SyntaxKind.None && nextToken.Kind() == SyntaxKind.SemicolonToken)
{
var forStatement = nextToken.GetAncestor<ForStatementSyntax>();
if (forStatement != null && forStatement.FirstSemicolonToken == nextToken)
{
return default;
}
lastToken = nextToken;
}
return lastToken;
}
private static string CreateCommentBannerTextWithPrefix(string text, string prefix)
{
Contract.ThrowIfNull(text);
Contract.ThrowIfNull(prefix);
var prefixLength = prefix.Length;
return prefix + " " + text.Substring(prefixLength).Trim() + " " + Ellipsis;
}
private static string GetCommentBannerText(SyntaxTrivia comment)
{
Contract.ThrowIfFalse(comment.IsSingleLineComment() || comment.IsMultiLineComment());
if (comment.IsSingleLineComment())
{
return CreateCommentBannerTextWithPrefix(comment.ToString(), "//");
}
else if (comment.IsMultiLineComment())
{
var lineBreakStart = comment.ToString().IndexOfAny(s_newLineCharacters);
var text = comment.ToString();
if (lineBreakStart >= 0)
{
text = text.Substring(0, lineBreakStart);
}
else
{
text = text.Length >= "/**/".Length && text.EndsWith(MultiLineCommentSuffix)
? text.Substring(0, text.Length - MultiLineCommentSuffix.Length)
: text;
}
return CreateCommentBannerTextWithPrefix(text, "/*");
}
else
{
return string.Empty;
}
}
private static BlockSpan CreateCommentBlockSpan(
SyntaxTrivia startComment, SyntaxTrivia endComment)
{
var span = TextSpan.FromBounds(startComment.SpanStart, endComment.Span.End);
return new BlockSpan(
isCollapsible: true,
textSpan: span,
hintSpan: span,
type: BlockTypes.Comment,
bannerText: GetCommentBannerText(startComment),
autoCollapse: true);
}
// For testing purposes
internal static ImmutableArray<BlockSpan> CreateCommentBlockSpan(
SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<BlockSpan>.Empty;
CollectCommentBlockSpans(triviaList, ref result.AsRef());
return result.ToImmutableAndClear();
}
public static void CollectCommentBlockSpans(
SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans)
{
if (triviaList.Count > 0)
{
SyntaxTrivia? startComment = null;
SyntaxTrivia? endComment = null;
void completeSingleLineCommentGroup(ref TemporaryArray<BlockSpan> spans)
{
if (startComment != null)
{
var singleLineCommentGroupRegion = CreateCommentBlockSpan(startComment.Value, endComment.Value);
spans.Add(singleLineCommentGroupRegion);
startComment = null;
endComment = null;
}
}
// Iterate through trivia and collect the following:
// 1. Groups of contiguous single-line comments that are only separated by whitespace
// 2. Multi-line comments
foreach (var trivia in triviaList)
{
if (trivia.IsSingleLineComment())
{
startComment ??= trivia;
endComment = trivia;
}
else if (trivia.IsMultiLineComment())
{
completeSingleLineCommentGroup(ref spans);
var multilineCommentRegion = CreateCommentBlockSpan(trivia, trivia);
spans.Add(multilineCommentRegion);
}
else if (!trivia.MatchesKind(SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndOfFileToken))
{
completeSingleLineCommentGroup(ref spans);
}
}
completeSingleLineCommentGroup(ref spans);
}
}
public static void CollectCommentBlockSpans(
SyntaxNode node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (optionProvider.IsMetadataAsSource && TryGetLeadingCollapsibleSpan(node, out var span))
{
spans.Add(span);
}
else
{
var triviaList = node.GetLeadingTrivia();
CollectCommentBlockSpans(triviaList, ref spans);
}
return;
// Local functions
static bool TryGetLeadingCollapsibleSpan(SyntaxNode node, out BlockSpan span)
{
var startToken = node.GetFirstToken();
var endToken = GetEndToken(node);
if (startToken.IsKind(SyntaxKind.None) || endToken.IsKind(SyntaxKind.None))
{
// if valid tokens can't be found then a meaningful span can't be generated
span = default;
return false;
}
var firstComment = startToken.LeadingTrivia.FirstOrNull(t => t.IsKind(SyntaxKind.SingleLineCommentTrivia));
var startPosition = firstComment.HasValue ? firstComment.Value.SpanStart : startToken.SpanStart;
var endPosition = endToken.SpanStart;
// TODO (tomescht): Mark the regions to be collapsed by default.
if (startPosition != endPosition)
{
var hintTextEndToken = GetHintTextEndToken(node);
span = new BlockSpan(
isCollapsible: true,
type: BlockTypes.Comment,
textSpan: TextSpan.FromBounds(startPosition, endPosition),
hintSpan: TextSpan.FromBounds(startPosition, hintTextEndToken.Span.End),
bannerText: Ellipsis,
autoCollapse: true);
return true;
}
span = default;
return false;
}
static SyntaxToken GetEndToken(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax constructorDeclaration))
{
return constructorDeclaration.Modifiers.FirstOrNull() ?? constructorDeclaration.Identifier;
}
else if (node.IsKind(SyntaxKind.ConversionOperatorDeclaration, out ConversionOperatorDeclarationSyntax conversionOperatorDeclaration))
{
return conversionOperatorDeclaration.Modifiers.FirstOrNull() ?? conversionOperatorDeclaration.ImplicitOrExplicitKeyword;
}
else if (node.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax delegateDeclaration))
{
return delegateDeclaration.Modifiers.FirstOrNull() ?? delegateDeclaration.DelegateKeyword;
}
else if (node.IsKind(SyntaxKind.DestructorDeclaration, out DestructorDeclarationSyntax destructorDeclaration))
{
return destructorDeclaration.TildeToken;
}
else if (node.IsKind(SyntaxKind.EnumDeclaration, out EnumDeclarationSyntax enumDeclaration))
{
return enumDeclaration.Modifiers.FirstOrNull() ?? enumDeclaration.EnumKeyword;
}
else if (node.IsKind(SyntaxKind.EnumMemberDeclaration, out EnumMemberDeclarationSyntax enumMemberDeclaration))
{
return enumMemberDeclaration.Identifier;
}
else if (node.IsKind(SyntaxKind.EventDeclaration, out EventDeclarationSyntax eventDeclaration))
{
return eventDeclaration.Modifiers.FirstOrNull() ?? eventDeclaration.EventKeyword;
}
else if (node.IsKind(SyntaxKind.EventFieldDeclaration, out EventFieldDeclarationSyntax eventFieldDeclaration))
{
return eventFieldDeclaration.Modifiers.FirstOrNull() ?? eventFieldDeclaration.EventKeyword;
}
else if (node.IsKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax fieldDeclaration))
{
return fieldDeclaration.Modifiers.FirstOrNull() ?? fieldDeclaration.Declaration.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax indexerDeclaration))
{
return indexerDeclaration.Modifiers.FirstOrNull() ?? indexerDeclaration.Type.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax methodDeclaration))
{
return methodDeclaration.Modifiers.FirstOrNull() ?? methodDeclaration.ReturnType.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.OperatorDeclaration, out OperatorDeclarationSyntax operatorDeclaration))
{
return operatorDeclaration.Modifiers.FirstOrNull() ?? operatorDeclaration.ReturnType.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax propertyDeclaration))
{
return propertyDeclaration.Modifiers.FirstOrNull() ?? propertyDeclaration.Type.GetFirstToken();
}
else if (node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or
SyntaxKind.RecordStructDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration)
{
var typeDeclaration = (TypeDeclarationSyntax)node;
return typeDeclaration.Modifiers.FirstOrNull() ?? typeDeclaration.Keyword;
}
else
{
return default;
}
}
static SyntaxToken GetHintTextEndToken(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.EnumDeclaration, out EnumDeclarationSyntax enumDeclaration))
{
return enumDeclaration.OpenBraceToken.GetPreviousToken();
}
else if (node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or
SyntaxKind.RecordStructDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration)
{
var typeDeclaration = (TypeDeclarationSyntax)node;
return typeDeclaration.OpenBraceToken.GetPreviousToken();
}
else
{
return node.GetLastToken();
}
}
}
private static BlockSpan CreateBlockSpan(
TextSpan textSpan, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
textSpan, textSpan, bannerText, autoCollapse, type, isCollapsible);
}
private static BlockSpan CreateBlockSpan(
TextSpan textSpan, TextSpan hintSpan,
string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return new BlockSpan(
textSpan: textSpan,
hintSpan: hintSpan,
bannerText: bannerText,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
public static BlockSpan CreateBlockSpan(
SyntaxNode node, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
node.Span,
bannerText,
autoCollapse,
type,
isCollapsible);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken syntaxToken, bool compressEmptyLines,
string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
node, syntaxToken, node.GetLastToken(), compressEmptyLines,
bannerText, autoCollapse, type, isCollapsible);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken,
int spanEndPos, int hintEndPos, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
// If the SyntaxToken is actually missing, don't attempt to create an outlining region.
if (startToken.IsMissing)
{
return null;
}
// Since we creating a span for everything after syntaxToken to ensure
// that it collapses properly. However, the hint span begins at the start
// of the next token so indentation in the tooltip is accurate.
var span = TextSpan.FromBounds(GetCollapsibleStart(startToken), spanEndPos);
var hintSpan = GetHintSpan(node, hintEndPos);
return CreateBlockSpan(
span,
hintSpan,
bannerText,
autoCollapse,
type,
isCollapsible);
}
private static TextSpan GetHintSpan(SyntaxNode node, int endPos)
{
// Don't include attributes in the BlockSpan for a node. When the user
// hovers over the indent-guide we don't want to show them the line with
// the attributes, we want to show them the line with the start of the
// actual structure.
foreach (var child in node.ChildNodesAndTokens())
{
if (child.Kind() != SyntaxKind.AttributeList)
{
return TextSpan.FromBounds(child.SpanStart, endPos);
}
}
return TextSpan.FromBounds(node.SpanStart, endPos);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken,
SyntaxToken endToken, bool compressEmptyLines, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
var (spanEnd, hintEnd) = GetCollapsibleEnd(endToken, compressEmptyLines);
return CreateBlockSpan(
node, startToken, spanEnd, hintEnd,
bannerText, autoCollapse, type, isCollapsible);
}
public static BlockSpan CreateBlockSpan(
SyntaxNode node, bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds everything after 'syntaxToken' up to and including the end
// of node as a region. The snippet to display is just "..."
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken syntaxToken, bool compressEmptyLines,
bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node, syntaxToken, compressEmptyLines,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds everything after 'syntaxToken' up to and including the end
// of node as a region. The snippet to display is just "..."
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken, SyntaxToken endToken, bool compressEmptyLines,
bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node, startToken, endToken, compressEmptyLines,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds the span surrounding the syntax list as a region. The
// snippet shown is the text from the first line of the first
// node in the list.
public static BlockSpan? CreateBlockSpan(
IEnumerable<SyntaxNode> syntaxList, bool compressEmptyLines, bool autoCollapse,
string type, bool isCollapsible)
{
if (syntaxList.IsEmpty())
{
return null;
}
var (end, hintEnd) = GetCollapsibleEnd(syntaxList.Last().GetLastToken(), compressEmptyLines);
var spanStart = syntaxList.First().GetFirstToken().FullSpan.End;
var spanEnd = end >= spanStart
? end
: spanStart;
var hintSpanStart = syntaxList.First().SpanStart;
var hintSpanEnd = hintEnd >= hintSpanStart
? hintEnd
: hintSpanStart;
return CreateBlockSpan(
textSpan: TextSpan.FromBounds(spanStart, spanEnd),
hintSpan: TextSpan.FromBounds(hintSpanStart, hintSpanEnd),
bannerText: Ellipsis,
autoCollapse: autoCollapse,
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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal static class CSharpStructureHelpers
{
public const string Ellipsis = "...";
public const string MultiLineCommentSuffix = "*/";
public const int MaxXmlDocCommentBannerLength = 120;
private static readonly char[] s_newLineCharacters = new char[] { '\r', '\n' };
private static int GetCollapsibleStart(SyntaxToken firstToken)
{
// If the *next* token has any leading comments, we use the end of the last one.
// If not, we check *this* token to see if it has any trailing comments and use the last one;
// otherwise, we use the end of this token.
var start = firstToken.Span.End;
var nextToken = firstToken.GetNextToken();
if (nextToken.Kind() != SyntaxKind.None && nextToken.HasLeadingTrivia)
{
var lastLeadingCommentTrivia = nextToken.LeadingTrivia.GetLastComment();
if (lastLeadingCommentTrivia != null)
{
start = lastLeadingCommentTrivia.Value.Span.End;
}
}
if (firstToken.HasTrailingTrivia)
{
var lastTrailingCommentOrWhitespaceTrivia = firstToken.TrailingTrivia.GetLastCommentOrWhitespace();
if (lastTrailingCommentOrWhitespaceTrivia != null)
{
start = lastTrailingCommentOrWhitespaceTrivia.Value.Span.End;
}
}
return start;
}
private static (int spanEnd, int hintEnd) GetCollapsibleEnd(SyntaxToken lastToken, bool compressEmptyLines)
{
// If the token has any trailing comments, we use the end of the token;
// otherwise, the behavior depends on 'compressEmptyLines':
// false: skip to the start of the first new line trivia
// true: skip to the start of the last new line trivia preceding a non-whitespace line
//
// The hint span never includes the compressed empty lines.
var trailingTrivia = lastToken.TrailingTrivia;
var nextLeadingTrivia = compressEmptyLines ? lastToken.GetNextToken(includeZeroWidth: true, includeSkipped: true).LeadingTrivia : default;
var end = lastToken.Span.End;
int? hintEnd = null;
foreach (var trivia in trailingTrivia)
{
if (!ProcessTrivia(trivia, compressEmptyLines, ref end, ref hintEnd))
return (end, hintEnd ?? end);
}
foreach (var trivia in nextLeadingTrivia)
{
if (!ProcessTrivia(trivia, compressEmptyLines, ref end, ref hintEnd))
return (end, hintEnd ?? end);
}
return (end, hintEnd ?? end);
// Return true to keep processing trivia; otherwise, false to return the current 'end'
static bool ProcessTrivia(SyntaxTrivia trivia, bool compressEmptyLines, ref int end, ref int? hintEnd)
{
if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
{
end = trivia.SpanStart;
hintEnd ??= end;
if (!compressEmptyLines)
return false;
}
else if (!trivia.IsKind(SyntaxKind.WhitespaceTrivia))
{
// We want this trivia to be visible even when the element is collapsed
return false;
}
return true;
}
}
public static SyntaxToken GetLastInlineMethodBlockToken(SyntaxNode node)
{
var lastToken = node.GetLastToken(includeZeroWidth: true);
if (lastToken.Kind() == SyntaxKind.None)
{
return default;
}
// If the next token is a semicolon, and we aren't in the initializer of a for-loop, use that token as the end.
var nextToken = lastToken.GetNextToken(includeSkipped: true);
if (nextToken.Kind() != SyntaxKind.None && nextToken.Kind() == SyntaxKind.SemicolonToken)
{
var forStatement = nextToken.GetAncestor<ForStatementSyntax>();
if (forStatement != null && forStatement.FirstSemicolonToken == nextToken)
{
return default;
}
lastToken = nextToken;
}
return lastToken;
}
private static string CreateCommentBannerTextWithPrefix(string text, string prefix)
{
Contract.ThrowIfNull(text);
Contract.ThrowIfNull(prefix);
var prefixLength = prefix.Length;
return prefix + " " + text.Substring(prefixLength).Trim() + " " + Ellipsis;
}
private static string GetCommentBannerText(SyntaxTrivia comment)
{
Contract.ThrowIfFalse(comment.IsSingleLineComment() || comment.IsMultiLineComment());
if (comment.IsSingleLineComment())
{
return CreateCommentBannerTextWithPrefix(comment.ToString(), "//");
}
else if (comment.IsMultiLineComment())
{
var lineBreakStart = comment.ToString().IndexOfAny(s_newLineCharacters);
var text = comment.ToString();
if (lineBreakStart >= 0)
{
text = text.Substring(0, lineBreakStart);
}
else
{
text = text.Length >= "/**/".Length && text.EndsWith(MultiLineCommentSuffix)
? text.Substring(0, text.Length - MultiLineCommentSuffix.Length)
: text;
}
return CreateCommentBannerTextWithPrefix(text, "/*");
}
else
{
return string.Empty;
}
}
private static BlockSpan CreateCommentBlockSpan(
SyntaxTrivia startComment, SyntaxTrivia endComment)
{
var span = TextSpan.FromBounds(startComment.SpanStart, endComment.Span.End);
return new BlockSpan(
isCollapsible: true,
textSpan: span,
hintSpan: span,
type: BlockTypes.Comment,
bannerText: GetCommentBannerText(startComment),
autoCollapse: true);
}
// For testing purposes
internal static ImmutableArray<BlockSpan> CreateCommentBlockSpan(
SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<BlockSpan>.Empty;
CollectCommentBlockSpans(triviaList, ref result.AsRef());
return result.ToImmutableAndClear();
}
public static void CollectCommentBlockSpans(
SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans)
{
if (triviaList.Count > 0)
{
SyntaxTrivia? startComment = null;
SyntaxTrivia? endComment = null;
void completeSingleLineCommentGroup(ref TemporaryArray<BlockSpan> spans)
{
if (startComment != null)
{
var singleLineCommentGroupRegion = CreateCommentBlockSpan(startComment.Value, endComment.Value);
spans.Add(singleLineCommentGroupRegion);
startComment = null;
endComment = null;
}
}
// Iterate through trivia and collect the following:
// 1. Groups of contiguous single-line comments that are only separated by whitespace
// 2. Multi-line comments
foreach (var trivia in triviaList)
{
if (trivia.IsSingleLineComment())
{
startComment ??= trivia;
endComment = trivia;
}
else if (trivia.IsMultiLineComment())
{
completeSingleLineCommentGroup(ref spans);
var multilineCommentRegion = CreateCommentBlockSpan(trivia, trivia);
spans.Add(multilineCommentRegion);
}
else if (!trivia.MatchesKind(SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndOfFileToken))
{
completeSingleLineCommentGroup(ref spans);
}
}
completeSingleLineCommentGroup(ref spans);
}
}
public static void CollectCommentBlockSpans(
SyntaxNode node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (optionProvider.IsMetadataAsSource && TryGetLeadingCollapsibleSpan(node, out var span))
{
spans.Add(span);
}
else
{
var triviaList = node.GetLeadingTrivia();
CollectCommentBlockSpans(triviaList, ref spans);
}
return;
// Local functions
static bool TryGetLeadingCollapsibleSpan(SyntaxNode node, out BlockSpan span)
{
var startToken = node.GetFirstToken();
var endToken = GetEndToken(node);
if (startToken.IsKind(SyntaxKind.None) || endToken.IsKind(SyntaxKind.None))
{
// if valid tokens can't be found then a meaningful span can't be generated
span = default;
return false;
}
var firstComment = startToken.LeadingTrivia.FirstOrNull(t => t.IsKind(SyntaxKind.SingleLineCommentTrivia));
var startPosition = firstComment.HasValue ? firstComment.Value.SpanStart : startToken.SpanStart;
var endPosition = endToken.SpanStart;
// TODO (tomescht): Mark the regions to be collapsed by default.
if (startPosition != endPosition)
{
var hintTextEndToken = GetHintTextEndToken(node);
span = new BlockSpan(
isCollapsible: true,
type: BlockTypes.Comment,
textSpan: TextSpan.FromBounds(startPosition, endPosition),
hintSpan: TextSpan.FromBounds(startPosition, hintTextEndToken.Span.End),
bannerText: Ellipsis,
autoCollapse: true);
return true;
}
span = default;
return false;
}
static SyntaxToken GetEndToken(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax constructorDeclaration))
{
return constructorDeclaration.Modifiers.FirstOrNull() ?? constructorDeclaration.Identifier;
}
else if (node.IsKind(SyntaxKind.ConversionOperatorDeclaration, out ConversionOperatorDeclarationSyntax conversionOperatorDeclaration))
{
return conversionOperatorDeclaration.Modifiers.FirstOrNull() ?? conversionOperatorDeclaration.ImplicitOrExplicitKeyword;
}
else if (node.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax delegateDeclaration))
{
return delegateDeclaration.Modifiers.FirstOrNull() ?? delegateDeclaration.DelegateKeyword;
}
else if (node.IsKind(SyntaxKind.DestructorDeclaration, out DestructorDeclarationSyntax destructorDeclaration))
{
return destructorDeclaration.TildeToken;
}
else if (node.IsKind(SyntaxKind.EnumDeclaration, out EnumDeclarationSyntax enumDeclaration))
{
return enumDeclaration.Modifiers.FirstOrNull() ?? enumDeclaration.EnumKeyword;
}
else if (node.IsKind(SyntaxKind.EnumMemberDeclaration, out EnumMemberDeclarationSyntax enumMemberDeclaration))
{
return enumMemberDeclaration.Identifier;
}
else if (node.IsKind(SyntaxKind.EventDeclaration, out EventDeclarationSyntax eventDeclaration))
{
return eventDeclaration.Modifiers.FirstOrNull() ?? eventDeclaration.EventKeyword;
}
else if (node.IsKind(SyntaxKind.EventFieldDeclaration, out EventFieldDeclarationSyntax eventFieldDeclaration))
{
return eventFieldDeclaration.Modifiers.FirstOrNull() ?? eventFieldDeclaration.EventKeyword;
}
else if (node.IsKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax fieldDeclaration))
{
return fieldDeclaration.Modifiers.FirstOrNull() ?? fieldDeclaration.Declaration.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax indexerDeclaration))
{
return indexerDeclaration.Modifiers.FirstOrNull() ?? indexerDeclaration.Type.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax methodDeclaration))
{
return methodDeclaration.Modifiers.FirstOrNull() ?? methodDeclaration.ReturnType.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.OperatorDeclaration, out OperatorDeclarationSyntax operatorDeclaration))
{
return operatorDeclaration.Modifiers.FirstOrNull() ?? operatorDeclaration.ReturnType.GetFirstToken();
}
else if (node.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax propertyDeclaration))
{
return propertyDeclaration.Modifiers.FirstOrNull() ?? propertyDeclaration.Type.GetFirstToken();
}
else if (node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or
SyntaxKind.RecordStructDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration)
{
var typeDeclaration = (TypeDeclarationSyntax)node;
return typeDeclaration.Modifiers.FirstOrNull() ?? typeDeclaration.Keyword;
}
else
{
return default;
}
}
static SyntaxToken GetHintTextEndToken(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.EnumDeclaration, out EnumDeclarationSyntax enumDeclaration))
{
return enumDeclaration.OpenBraceToken.GetPreviousToken();
}
else if (node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or
SyntaxKind.RecordStructDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration)
{
var typeDeclaration = (TypeDeclarationSyntax)node;
return typeDeclaration.OpenBraceToken.GetPreviousToken();
}
else
{
return node.GetLastToken();
}
}
}
private static BlockSpan CreateBlockSpan(
TextSpan textSpan, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
textSpan, textSpan, bannerText, autoCollapse, type, isCollapsible);
}
private static BlockSpan CreateBlockSpan(
TextSpan textSpan, TextSpan hintSpan,
string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return new BlockSpan(
textSpan: textSpan,
hintSpan: hintSpan,
bannerText: bannerText,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
public static BlockSpan CreateBlockSpan(
SyntaxNode node, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
node.Span,
bannerText,
autoCollapse,
type,
isCollapsible);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken syntaxToken, bool compressEmptyLines,
string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
return CreateBlockSpan(
node, syntaxToken, node.GetLastToken(), compressEmptyLines,
bannerText, autoCollapse, type, isCollapsible);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken,
int spanEndPos, int hintEndPos, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
// If the SyntaxToken is actually missing, don't attempt to create an outlining region.
if (startToken.IsMissing)
{
return null;
}
// Since we creating a span for everything after syntaxToken to ensure
// that it collapses properly. However, the hint span begins at the start
// of the next token so indentation in the tooltip is accurate.
var span = TextSpan.FromBounds(GetCollapsibleStart(startToken), spanEndPos);
var hintSpan = GetHintSpan(node, hintEndPos);
return CreateBlockSpan(
span,
hintSpan,
bannerText,
autoCollapse,
type,
isCollapsible);
}
private static TextSpan GetHintSpan(SyntaxNode node, int endPos)
{
// Don't include attributes in the BlockSpan for a node. When the user
// hovers over the indent-guide we don't want to show them the line with
// the attributes, we want to show them the line with the start of the
// actual structure.
foreach (var child in node.ChildNodesAndTokens())
{
if (child.Kind() != SyntaxKind.AttributeList)
{
return TextSpan.FromBounds(child.SpanStart, endPos);
}
}
return TextSpan.FromBounds(node.SpanStart, endPos);
}
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken,
SyntaxToken endToken, bool compressEmptyLines, string bannerText, bool autoCollapse,
string type, bool isCollapsible)
{
var (spanEnd, hintEnd) = GetCollapsibleEnd(endToken, compressEmptyLines);
return CreateBlockSpan(
node, startToken, spanEnd, hintEnd,
bannerText, autoCollapse, type, isCollapsible);
}
public static BlockSpan CreateBlockSpan(
SyntaxNode node, bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds everything after 'syntaxToken' up to and including the end
// of node as a region. The snippet to display is just "..."
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken syntaxToken, bool compressEmptyLines,
bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node, syntaxToken, compressEmptyLines,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds everything after 'syntaxToken' up to and including the end
// of node as a region. The snippet to display is just "..."
public static BlockSpan? CreateBlockSpan(
SyntaxNode node, SyntaxToken startToken, SyntaxToken endToken, bool compressEmptyLines,
bool autoCollapse, string type, bool isCollapsible)
{
return CreateBlockSpan(
node, startToken, endToken, compressEmptyLines,
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
// Adds the span surrounding the syntax list as a region. The
// snippet shown is the text from the first line of the first
// node in the list.
public static BlockSpan? CreateBlockSpan(
IEnumerable<SyntaxNode> syntaxList, bool compressEmptyLines, bool autoCollapse,
string type, bool isCollapsible)
{
if (syntaxList.IsEmpty())
{
return null;
}
var (end, hintEnd) = GetCollapsibleEnd(syntaxList.Last().GetLastToken(), compressEmptyLines);
var spanStart = syntaxList.First().GetFirstToken().FullSpan.End;
var spanEnd = end >= spanStart
? end
: spanStart;
var hintSpanStart = syntaxList.First().SpanStart;
var hintSpanEnd = hintEnd >= hintSpanStart
? hintEnd
: hintSpanStart;
return CreateBlockSpan(
textSpan: TextSpan.FromBounds(spanStart, spanEnd),
hintSpan: TextSpan.FromBounds(hintSpanStart, hintSpanEnd),
bannerText: Ellipsis,
autoCollapse: autoCollapse,
type: type,
isCollapsible: isCollapsible);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./.git/hooks/fsmonitor-watchman.sample | #!/usr/bin/perl
use strict;
use warnings;
use IPC::Open2;
# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 1) and a time in nanoseconds
# formatted as a string and outputs to stdout all files that have been
# modified since the given time. Paths must be relative to the root of
# the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $time) = @ARGV;
# Check the hook interface version
if ($version == 1) {
# convert nanoseconds to seconds
# subtract one second to make sure watchman will return all changes
$time = int ($time / 1000000000) - 1;
} else {
die "Unsupported query-fsmonitor hook version '$version'.\n" .
"Falling back to scanning...\n";
}
my $git_work_tree;
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
$git_work_tree = Win32::GetCwd();
$git_work_tree =~ tr/\\/\//;
} else {
require Cwd;
$git_work_tree = Cwd::cwd();
}
my $retry = 1;
launch_watchman();
sub launch_watchman {
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
or die "open2() failed: $!\n" .
"Falling back to scanning...\n";
# In the query expression below we're asking for names of files that
# changed since $time but were not transient (ie created after
# $time but no longer exist).
#
# To accomplish this, we're using the "since" generator to use the
# recency index to select candidate nodes and "fields" to limit the
# output to file names only.
my $query = <<" END";
["query", "$git_work_tree", {
"since": $time,
"fields": ["name"]
}]
END
print CHLD_IN $query;
close CHLD_IN;
my $response = do {local $/; <CHLD_OUT>};
die "Watchman: command returned no output.\n" .
"Falling back to scanning...\n" if $response eq "";
die "Watchman: command returned invalid output: $response\n" .
"Falling back to scanning...\n" unless $response =~ /^\{/;
my $json_pkg;
eval {
require JSON::XS;
$json_pkg = "JSON::XS";
1;
} or do {
require JSON::PP;
$json_pkg = "JSON::PP";
};
my $o = $json_pkg->new->utf8->decode($response);
if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) {
print STDERR "Adding '$git_work_tree' to watchman's watch list.\n";
$retry--;
qx/watchman watch "$git_work_tree"/;
die "Failed to make watchman watch '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
# Watchman will always return all files on the first query so
# return the fast "everything is dirty" flag to git and do the
# Watchman query just to get it over with now so we won't pay
# the cost in git to look up each individual file.
print "/\0";
eval { launch_watchman() };
exit 0;
}
die "Watchman: $o->{error}.\n" .
"Falling back to scanning...\n" if $o->{error};
binmode STDOUT, ":utf8";
local $, = "\0";
print @{$o->{files}};
}
| #!/usr/bin/perl
use strict;
use warnings;
use IPC::Open2;
# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 1) and a time in nanoseconds
# formatted as a string and outputs to stdout all files that have been
# modified since the given time. Paths must be relative to the root of
# the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $time) = @ARGV;
# Check the hook interface version
if ($version == 1) {
# convert nanoseconds to seconds
# subtract one second to make sure watchman will return all changes
$time = int ($time / 1000000000) - 1;
} else {
die "Unsupported query-fsmonitor hook version '$version'.\n" .
"Falling back to scanning...\n";
}
my $git_work_tree;
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
$git_work_tree = Win32::GetCwd();
$git_work_tree =~ tr/\\/\//;
} else {
require Cwd;
$git_work_tree = Cwd::cwd();
}
my $retry = 1;
launch_watchman();
sub launch_watchman {
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
or die "open2() failed: $!\n" .
"Falling back to scanning...\n";
# In the query expression below we're asking for names of files that
# changed since $time but were not transient (ie created after
# $time but no longer exist).
#
# To accomplish this, we're using the "since" generator to use the
# recency index to select candidate nodes and "fields" to limit the
# output to file names only.
my $query = <<" END";
["query", "$git_work_tree", {
"since": $time,
"fields": ["name"]
}]
END
print CHLD_IN $query;
close CHLD_IN;
my $response = do {local $/; <CHLD_OUT>};
die "Watchman: command returned no output.\n" .
"Falling back to scanning...\n" if $response eq "";
die "Watchman: command returned invalid output: $response\n" .
"Falling back to scanning...\n" unless $response =~ /^\{/;
my $json_pkg;
eval {
require JSON::XS;
$json_pkg = "JSON::XS";
1;
} or do {
require JSON::PP;
$json_pkg = "JSON::PP";
};
my $o = $json_pkg->new->utf8->decode($response);
if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) {
print STDERR "Adding '$git_work_tree' to watchman's watch list.\n";
$retry--;
qx/watchman watch "$git_work_tree"/;
die "Failed to make watchman watch '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
# Watchman will always return all files on the first query so
# return the fast "everything is dirty" flag to git and do the
# Watchman query just to get it over with now so we won't pay
# the cost in git to look up each individual file.
print "/\0";
eval { launch_watchman() };
exit 0;
}
die "Watchman: $o->{error}.\n" .
"Falling back to scanning...\n" if $o->{error};
binmode STDOUT, ":utf8";
local $, = "\0";
print @{$o->{files}};
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.Editor.Implementation.Organizing;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing
{
public class OrganizeTypeDeclarationTests : AbstractOrganizerTests
{
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestFieldsWithoutInitializers1(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("struct")]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestNestedTypes(string typeKind)
{
var initial =
$@"class C {{
{typeKind} Nested1 {{ }}
{typeKind} Nested2 {{ }}
int A;
}}";
var final =
$@"class C {{
int A;
{typeKind} Nested1 {{ }}
{typeKind} Nested2 {{ }}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestFieldsWithoutInitializers2(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C;
int B;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record struct")]
public async Task TestFieldsWithInitializers1(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C = 0;
int B;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C = 0;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestFieldsWithInitializers2(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C = 0;
int B = 0;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int C = 0;
int B = 0;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestEventFieldDeclaration(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public event EventHandler MyEvent;
}}";
var final =
$@"{typeKind} C {{
public event EventHandler MyEvent;
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestEventDeclaration(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public event EventHandler Event
{{
remove {{ }}
add {{ }}
}}
public static int Property {{ get; set; }}
}}";
var final =
$@"{typeKind} C {{
public static int Property {{ get; set; }}
public event EventHandler Event
{{
remove {{ }}
add {{ }}
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestOperator(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public static int operator +(Goo<T> a, int b)
{{
return 1;
}}
}}";
var final =
$@"{typeKind} C {{
public static int operator +(Goo<T> a, int b)
{{
return 1;
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestIndexer(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public T this[int i]
{{
get
{{
return default(T);
}}
}}
C() {{}}
}}";
var final =
$@"{typeKind} C {{
C() {{}}
public T this[int i]
{{
get
{{
return default(T);
}}
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestConstructorAndDestructors(string typeKind)
{
var initial =
$@"{typeKind} C {{
public ~Goo() {{}}
enum Days {{Sat, Sun}};
public Goo() {{}}
}}";
var final =
$@"{typeKind} C {{
public Goo() {{}}
public ~Goo() {{}}
enum Days {{Sat, Sun}};
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInterface(string typeKind)
{
var initial =
$@"{typeKind} C {{}}
interface I
{{
void Goo();
int Property {{ get; set; }}
event EventHandler Event;
}}";
var final =
$@"{typeKind} C {{}}
interface I
{{
event EventHandler Event;
int Property {{ get; set; }}
void Goo();
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestStaticInstance(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
static int B;
int C;
static int D;
}}";
var final =
$@"{typeKind} C {{
static int B;
static int D;
int A;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record struct")]
public async Task TestAccessibility(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
private int B;
internal int C;
protected int D;
public int E;
protected internal int F;
}}";
var final =
$@"{typeKind} C {{
public int E;
protected int D;
protected internal int F;
internal int C;
int A;
private int B;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestStaticAccessibility(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A1;
private int B1;
internal int C1;
protected int D1;
public int E1;
static int A2;
static private int B2;
static internal int C2;
static protected int D2;
static public int E2;
}}";
var final =
$@"{typeKind} C {{
public static int E2;
protected static int D2;
internal static int C2;
static int A2;
private static int B2;
public int E1;
protected int D1;
internal int C1;
int A1;
private int B1;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestGenerics(string typeKind)
{
var initial =
$@"{typeKind} C {{
void B<X,Y>();
void B<Z>();
void B();
void A<X,Y>();
void A<Z>();
void A();
}}";
var final =
$@"{typeKind} C {{
void A();
void A<Z>();
void A<X,Y>();
void B();
void B<Z>();
void B<X,Y>();
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion(string typeKind)
{
var initial =
$@"{typeKind} C {{
#if true
int c;
int b;
int a;
#endif
}}";
var final =
$@"{typeKind} C {{
#if true
int a;
int b;
int c;
#endif
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion2(string typeKind)
{
var initial =
$@"{typeKind} C {{
#if true
int z;
int y;
int x;
#endif
#if true
int c;
int b;
int a;
#endif
}}";
var final =
$@"{typeKind} C {{
#if true
int x;
int y;
int z;
#endif
#if true
int a;
int b;
int c;
#endif
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion3(string typeKind)
{
var initial =
$@"{typeKind} C {{
int z;
int y;
#if true
int x;
int c;
#endif
int b;
int a;
}}";
var final =
$@"{typeKind} C {{
int y;
int z;
#if true
int c;
int x;
#endif
int a;
int b;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion4(string typeKind)
{
var initial =
$@"{typeKind} C {{
int c() {{
}}
int b {{
}}
int a {{
#if true
#endif
}}
}}";
var final =
$@"{typeKind} C {{
int a {{
#if true
#endif
}}
int b {{
}}
int c() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion5(string typeKind)
{
var initial =
$@"{typeKind} C {{
int c() {{
}}
int b {{
}}
int a {{
#if true
#else
#endif
}}
}}";
var final =
$@"{typeKind} C {{
int a {{
#if true
#else
#endif
}}
int b {{
}}
int c() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion6(string typeKind)
{
var initial =
$@"{typeKind} C {{
#region
int e() {{
}}
int d() {{
}}
int c() {{
#region
}}
#endregion
int b {{
}}
int a {{
}}
#endregion
}}";
var final =
$@"{typeKind} C {{
#region
int d() {{
}}
int e() {{
}}
int c() {{
#region
}}
#endregion
int a {{
}}
int b {{
}}
#endregion
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestPinned(string typeKind)
{
var initial =
$@"{typeKind} C {{
int z() {{
}}
int y() {{
}}
int x() {{
#if true
}}
int n;
int m;
int c() {{
#endif
}}
int b() {{
}}
int a() {{
}}
}}";
var final =
$@"{typeKind} C {{
int y() {{
}}
int z() {{
}}
int x() {{
#if true
}}
int m;
int n;
int c() {{
#endif
}}
int a() {{
}}
int b() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestSensitivity(string typeKind)
{
var initial =
$@"{typeKind} C {{
int Bb;
int B;
int bB;
int b;
int Aa;
int a;
int A;
int aa;
int aA;
int AA;
int bb;
int BB;
int bBb;
int bbB;
int あ;
int ア;
int ア;
int ああ;
int あア;
int あア;
int アあ;
int cC;
int Cc;
int アア;
int アア;
int アあ;
int アア;
int アア;
int BBb;
int BbB;
int bBB;
int BBB;
int c;
int C;
int bbb;
int Bbb;
int cc;
int cC;
int CC;
}}";
var final =
$@"{typeKind} C {{
int a;
int A;
int aa;
int aA;
int Aa;
int AA;
int b;
int B;
int bb;
int bB;
int Bb;
int BB;
int bbb;
int bbB;
int bBb;
int bBB;
int Bbb;
int BbB;
int BBb;
int BBB;
int c;
int C;
int cc;
int cC;
int cC;
int Cc;
int CC;
int ア;
int ア;
int あ;
int アア;
int アア;
int アア;
int アア;
int アあ;
int アあ;
int あア;
int あア;
int ああ;
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods3(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods4(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods5(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods6(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveComments1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveComments2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// B
void B()
{{
}}
// A
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// A
void A()
{{
}}
// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveDocComments1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
/// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
/// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveDocComments2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
/// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
/// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestDontMoveBanner(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// Banner
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// Banner
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestDontMoveBanner2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// Banner
// More banner
// Bannery stuff
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// Banner
// More banner
// Bannery stuff
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Organizing)]
[Trait(Traits.Feature, Traits.Features.Interactive)]
public void OrganizingCommandsDisabledInSubmission()
{
using var workspace = TestWorkspace.Create(XElement.Parse(@"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
class C
{
object $$goo;
}
</Submission>
</Workspace> "),
workspaceKind: WorkspaceKind.Interactive,
composition: EditorTestCompositions.EditorFeaturesWpf);
// Force initialization.
workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList();
var textView = workspace.Documents.Single().GetTextView();
var handler = new OrganizeDocumentCommandHandler(workspace.ExportProvider.GetExportedValue<IThreadingContext>());
var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
state = handler.GetCommandState(new OrganizeDocumentCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.Editor.Implementation.Organizing;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Organizing
{
public class OrganizeTypeDeclarationTests : AbstractOrganizerTests
{
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestFieldsWithoutInitializers1(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("struct")]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestNestedTypes(string typeKind)
{
var initial =
$@"class C {{
{typeKind} Nested1 {{ }}
{typeKind} Nested2 {{ }}
int A;
}}";
var final =
$@"class C {{
int A;
{typeKind} Nested1 {{ }}
{typeKind} Nested2 {{ }}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestFieldsWithoutInitializers2(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C;
int B;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record struct")]
public async Task TestFieldsWithInitializers1(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C = 0;
int B;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int B;
int C = 0;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestFieldsWithInitializers2(string typeKind)
{
var initial =
$@"{typeKind} C {{
int C = 0;
int B = 0;
int A;
}}";
var final =
$@"{typeKind} C {{
int A;
int C = 0;
int B = 0;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestEventFieldDeclaration(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public event EventHandler MyEvent;
}}";
var final =
$@"{typeKind} C {{
public event EventHandler MyEvent;
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestEventDeclaration(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public event EventHandler Event
{{
remove {{ }}
add {{ }}
}}
public static int Property {{ get; set; }}
}}";
var final =
$@"{typeKind} C {{
public static int Property {{ get; set; }}
public event EventHandler Event
{{
remove {{ }}
add {{ }}
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestOperator(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public static int operator +(Goo<T> a, int b)
{{
return 1;
}}
}}";
var final =
$@"{typeKind} C {{
public static int operator +(Goo<T> a, int b)
{{
return 1;
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestIndexer(string typeKind)
{
var initial =
$@"{typeKind} C {{
public void Goo() {{}}
public T this[int i]
{{
get
{{
return default(T);
}}
}}
C() {{}}
}}";
var final =
$@"{typeKind} C {{
C() {{}}
public T this[int i]
{{
get
{{
return default(T);
}}
}}
public void Goo() {{}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestConstructorAndDestructors(string typeKind)
{
var initial =
$@"{typeKind} C {{
public ~Goo() {{}}
enum Days {{Sat, Sun}};
public Goo() {{}}
}}";
var final =
$@"{typeKind} C {{
public Goo() {{}}
public ~Goo() {{}}
enum Days {{Sat, Sun}};
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInterface(string typeKind)
{
var initial =
$@"{typeKind} C {{}}
interface I
{{
void Goo();
int Property {{ get; set; }}
event EventHandler Event;
}}";
var final =
$@"{typeKind} C {{}}
interface I
{{
event EventHandler Event;
int Property {{ get; set; }}
void Goo();
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestStaticInstance(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
static int B;
int C;
static int D;
}}";
var final =
$@"{typeKind} C {{
static int B;
static int D;
int A;
int C;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
[InlineData("record struct")]
public async Task TestAccessibility(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A;
private int B;
internal int C;
protected int D;
public int E;
protected internal int F;
}}";
var final =
$@"{typeKind} C {{
public int E;
protected int D;
protected internal int F;
internal int C;
int A;
private int B;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestStaticAccessibility(string typeKind)
{
var initial =
$@"{typeKind} C {{
int A1;
private int B1;
internal int C1;
protected int D1;
public int E1;
static int A2;
static private int B2;
static internal int C2;
static protected int D2;
static public int E2;
}}";
var final =
$@"{typeKind} C {{
public static int E2;
protected static int D2;
internal static int C2;
static int A2;
private static int B2;
public int E1;
protected int D1;
internal int C1;
int A1;
private int B1;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestGenerics(string typeKind)
{
var initial =
$@"{typeKind} C {{
void B<X,Y>();
void B<Z>();
void B();
void A<X,Y>();
void A<Z>();
void A();
}}";
var final =
$@"{typeKind} C {{
void A();
void A<Z>();
void A<X,Y>();
void B();
void B<Z>();
void B<X,Y>();
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion(string typeKind)
{
var initial =
$@"{typeKind} C {{
#if true
int c;
int b;
int a;
#endif
}}";
var final =
$@"{typeKind} C {{
#if true
int a;
int b;
int c;
#endif
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion2(string typeKind)
{
var initial =
$@"{typeKind} C {{
#if true
int z;
int y;
int x;
#endif
#if true
int c;
int b;
int a;
#endif
}}";
var final =
$@"{typeKind} C {{
#if true
int x;
int y;
int z;
#endif
#if true
int a;
int b;
int c;
#endif
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion3(string typeKind)
{
var initial =
$@"{typeKind} C {{
int z;
int y;
#if true
int x;
int c;
#endif
int b;
int a;
}}";
var final =
$@"{typeKind} C {{
int y;
int z;
#if true
int c;
int x;
#endif
int a;
int b;
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion4(string typeKind)
{
var initial =
$@"{typeKind} C {{
int c() {{
}}
int b {{
}}
int a {{
#if true
#endif
}}
}}";
var final =
$@"{typeKind} C {{
int a {{
#if true
#endif
}}
int b {{
}}
int c() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion5(string typeKind)
{
var initial =
$@"{typeKind} C {{
int c() {{
}}
int b {{
}}
int a {{
#if true
#else
#endif
}}
}}";
var final =
$@"{typeKind} C {{
int a {{
#if true
#else
#endif
}}
int b {{
}}
int c() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestInsidePPRegion6(string typeKind)
{
var initial =
$@"{typeKind} C {{
#region
int e() {{
}}
int d() {{
}}
int c() {{
#region
}}
#endregion
int b {{
}}
int a {{
}}
#endregion
}}";
var final =
$@"{typeKind} C {{
#region
int d() {{
}}
int e() {{
}}
int c() {{
#region
}}
#endregion
int a {{
}}
int b {{
}}
#endregion
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestPinned(string typeKind)
{
var initial =
$@"{typeKind} C {{
int z() {{
}}
int y() {{
}}
int x() {{
#if true
}}
int n;
int m;
int c() {{
#endif
}}
int b() {{
}}
int a() {{
}}
}}";
var final =
$@"{typeKind} C {{
int y() {{
}}
int z() {{
}}
int x() {{
#if true
}}
int m;
int n;
int c() {{
#endif
}}
int a() {{
}}
int b() {{
}}
}}";
await CheckAsync(initial, final);
}
[Theory, Trait(Traits.Feature, Traits.Features.Organizing)]
[InlineData("class")]
[InlineData("record")]
public async Task TestSensitivity(string typeKind)
{
var initial =
$@"{typeKind} C {{
int Bb;
int B;
int bB;
int b;
int Aa;
int a;
int A;
int aa;
int aA;
int AA;
int bb;
int BB;
int bBb;
int bbB;
int あ;
int ア;
int ア;
int ああ;
int あア;
int あア;
int アあ;
int cC;
int Cc;
int アア;
int アア;
int アあ;
int アア;
int アア;
int BBb;
int BbB;
int bBB;
int BBB;
int c;
int C;
int bbb;
int Bbb;
int cc;
int cC;
int CC;
}}";
var final =
$@"{typeKind} C {{
int a;
int A;
int aa;
int aA;
int Aa;
int AA;
int b;
int B;
int bb;
int bB;
int Bb;
int BB;
int bbb;
int bbB;
int bBb;
int bBB;
int Bbb;
int BbB;
int BBb;
int BBB;
int c;
int C;
int cc;
int cC;
int cC;
int Cc;
int CC;
int ア;
int ア;
int あ;
int アア;
int アア;
int アア;
int アア;
int アあ;
int アあ;
int あア;
int あア;
int ああ;
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods3(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods4(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods5(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestWhitespaceBetweenMethods6(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveComments1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveComments2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// B
void B()
{{
}}
// A
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// A
void A()
{{
}}
// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveDocComments1(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
/// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
/// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestMoveDocComments2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
/// B
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
void A()
{{
}}
/// B
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestDontMoveBanner(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// Banner
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// Banner
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WorkItem(537614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537614")]
[Theory]
[InlineData("class")]
[InlineData("record")]
public async Task TestDontMoveBanner2(string typeKind)
{
var initial =
$@"{typeKind} Program
{{
// Banner
// More banner
// Bannery stuff
void B()
{{
}}
void A()
{{
}}
}}";
var final =
$@"{typeKind} Program
{{
// Banner
// More banner
// Bannery stuff
void A()
{{
}}
void B()
{{
}}
}}";
await CheckAsync(initial, final);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Organizing)]
[Trait(Traits.Feature, Traits.Features.Interactive)]
public void OrganizingCommandsDisabledInSubmission()
{
using var workspace = TestWorkspace.Create(XElement.Parse(@"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
class C
{
object $$goo;
}
</Submission>
</Workspace> "),
workspaceKind: WorkspaceKind.Interactive,
composition: EditorTestCompositions.EditorFeaturesWpf);
// Force initialization.
workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList();
var textView = workspace.Documents.Single().GetTextView();
var handler = new OrganizeDocumentCommandHandler(workspace.ExportProvider.GetExportedValue<IThreadingContext>());
var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
state = handler.GetCommandState(new OrganizeDocumentCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/Core/Portable/Serialization/AbstractOptionsSerializationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
internal abstract class AbstractOptionsSerializationService : IOptionsSerializationService
{
public abstract void WriteTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken);
public abstract void WriteTo(ParseOptions options, ObjectWriter writer);
public abstract CompilationOptions ReadCompilationOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
public abstract ParseOptions ReadParseOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
protected static void WriteCompilationOptionsTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32((int)options.OutputKind);
writer.WriteBoolean(options.ReportSuppressedDiagnostics);
writer.WriteString(options.ModuleName);
writer.WriteString(options.MainTypeName);
writer.WriteString(options.ScriptClassName);
writer.WriteInt32((int)options.OptimizationLevel);
writer.WriteBoolean(options.CheckOverflow);
// REVIEW: is it okay this being not part of snapshot?
writer.WriteString(options.CryptoKeyContainer);
writer.WriteString(options.CryptoKeyFile);
writer.WriteValue(options.CryptoPublicKey.AsSpan());
writer.WriteBoolean(options.DelaySign.HasValue);
if (options.DelaySign.HasValue)
{
writer.WriteBoolean(options.DelaySign.Value);
}
writer.WriteInt32((int)options.Platform);
writer.WriteInt32((int)options.GeneralDiagnosticOption);
writer.WriteInt32(options.WarningLevel);
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
writer.WriteInt32(options.SpecificDiagnosticOptions.Count);
foreach (var kv in options.SpecificDiagnosticOptions.OrderBy(o => o.Key))
{
writer.WriteString(kv.Key);
writer.WriteInt32((int)kv.Value);
}
writer.WriteBoolean(options.ConcurrentBuild);
writer.WriteBoolean(options.Deterministic);
writer.WriteBoolean(options.PublicSign);
writer.WriteByte((byte)options.MetadataImportOptions);
// REVIEW: What should I do with these. we probably need to implement either out own one
// or somehow share these as service....
//
// XmlReferenceResolver xmlReferenceResolver
// SourceReferenceResolver sourceReferenceResolver
// MetadataReferenceResolver metadataReferenceResolver
// AssemblyIdentityComparer assemblyIdentityComparer
// StrongNameProvider strongNameProvider
}
protected static void ReadCompilationOptionsFrom(
ObjectReader reader,
out OutputKind outputKind,
out bool reportSuppressedDiagnostics,
out string moduleName,
out string mainTypeName,
out string scriptClassName,
out OptimizationLevel optimizationLevel,
out bool checkOverflow,
out string cryptoKeyContainer,
out string cryptoKeyFile,
out ImmutableArray<byte> cryptoPublicKey,
out bool? delaySign,
out Platform platform,
out ReportDiagnostic generalDiagnosticOption,
out int warningLevel,
out IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
out bool concurrentBuild,
out bool deterministic,
out bool publicSign,
out MetadataImportOptions metadataImportOptions,
out XmlReferenceResolver xmlReferenceResolver,
out SourceReferenceResolver sourceReferenceResolver,
out MetadataReferenceResolver metadataReferenceResolver,
out AssemblyIdentityComparer assemblyIdentityComparer,
out StrongNameProvider strongNameProvider,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
outputKind = (OutputKind)reader.ReadInt32();
reportSuppressedDiagnostics = reader.ReadBoolean();
moduleName = reader.ReadString();
mainTypeName = reader.ReadString();
scriptClassName = reader.ReadString();
optimizationLevel = (OptimizationLevel)reader.ReadInt32();
checkOverflow = reader.ReadBoolean();
// REVIEW: is it okay this being not part of snapshot?
cryptoKeyContainer = reader.ReadString();
cryptoKeyFile = reader.ReadString();
cryptoPublicKey = reader.ReadArray<byte>().ToImmutableArrayOrEmpty();
delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;
platform = (Platform)reader.ReadInt32();
generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();
warningLevel = reader.ReadInt32();
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
// not sure why CompilationOptions uses SequencialEqual to check options equality
// when ordering can change result of it even if contents are same.
var count = reader.ReadInt32();
List<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptionsList = null;
if (count > 0)
{
specificDiagnosticOptionsList = new List<KeyValuePair<string, ReportDiagnostic>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadString();
var value = (ReportDiagnostic)reader.ReadInt32();
specificDiagnosticOptionsList.Add(KeyValuePairUtil.Create(key, value));
}
}
specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, ReportDiagnostic>>();
concurrentBuild = reader.ReadBoolean();
deterministic = reader.ReadBoolean();
publicSign = reader.ReadBoolean();
metadataImportOptions = (MetadataImportOptions)reader.ReadByte();
// REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
// compiler.
xmlReferenceResolver = XmlFileResolver.Default;
sourceReferenceResolver = SourceFileResolver.Default;
metadataReferenceResolver = null;
assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
strongNameProvider = new DesktopStrongNameProvider();
}
protected static void WriteParseOptionsTo(ParseOptions options, ObjectWriter writer)
{
writer.WriteInt32((int)options.Kind);
writer.WriteInt32((int)options.DocumentationMode);
// REVIEW: I don't think there is a guarantee on ordering of elements in the readonly dictionary.
// unfortunately, we need to sort them to make it deterministic
writer.WriteInt32(options.Features.Count);
foreach (var kv in options.Features.OrderBy(o => o.Key))
{
writer.WriteString(kv.Key);
writer.WriteString(kv.Value);
}
}
protected static void ReadParseOptionsFrom(
ObjectReader reader,
out SourceCodeKind kind,
out DocumentationMode documentationMode,
out IEnumerable<KeyValuePair<string, string>> features,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
kind = (SourceCodeKind)reader.ReadInt32();
documentationMode = (DocumentationMode)reader.ReadInt32();
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
// not sure why ParseOptions uses SequencialEqual to check options equality
// when ordering can change result of it even if contents are same.
var count = reader.ReadInt32();
List<KeyValuePair<string, string>> featuresList = null;
if (count > 0)
{
featuresList = new List<KeyValuePair<string, string>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadString();
var value = reader.ReadString();
featuresList.Add(KeyValuePairUtil.Create(key, value));
}
}
features = featuresList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, string>>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
internal abstract class AbstractOptionsSerializationService : IOptionsSerializationService
{
public abstract void WriteTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken);
public abstract void WriteTo(ParseOptions options, ObjectWriter writer);
public abstract CompilationOptions ReadCompilationOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
public abstract ParseOptions ReadParseOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
protected static void WriteCompilationOptionsTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32((int)options.OutputKind);
writer.WriteBoolean(options.ReportSuppressedDiagnostics);
writer.WriteString(options.ModuleName);
writer.WriteString(options.MainTypeName);
writer.WriteString(options.ScriptClassName);
writer.WriteInt32((int)options.OptimizationLevel);
writer.WriteBoolean(options.CheckOverflow);
// REVIEW: is it okay this being not part of snapshot?
writer.WriteString(options.CryptoKeyContainer);
writer.WriteString(options.CryptoKeyFile);
writer.WriteValue(options.CryptoPublicKey.AsSpan());
writer.WriteBoolean(options.DelaySign.HasValue);
if (options.DelaySign.HasValue)
{
writer.WriteBoolean(options.DelaySign.Value);
}
writer.WriteInt32((int)options.Platform);
writer.WriteInt32((int)options.GeneralDiagnosticOption);
writer.WriteInt32(options.WarningLevel);
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
writer.WriteInt32(options.SpecificDiagnosticOptions.Count);
foreach (var kv in options.SpecificDiagnosticOptions.OrderBy(o => o.Key))
{
writer.WriteString(kv.Key);
writer.WriteInt32((int)kv.Value);
}
writer.WriteBoolean(options.ConcurrentBuild);
writer.WriteBoolean(options.Deterministic);
writer.WriteBoolean(options.PublicSign);
writer.WriteByte((byte)options.MetadataImportOptions);
// REVIEW: What should I do with these. we probably need to implement either out own one
// or somehow share these as service....
//
// XmlReferenceResolver xmlReferenceResolver
// SourceReferenceResolver sourceReferenceResolver
// MetadataReferenceResolver metadataReferenceResolver
// AssemblyIdentityComparer assemblyIdentityComparer
// StrongNameProvider strongNameProvider
}
protected static void ReadCompilationOptionsFrom(
ObjectReader reader,
out OutputKind outputKind,
out bool reportSuppressedDiagnostics,
out string moduleName,
out string mainTypeName,
out string scriptClassName,
out OptimizationLevel optimizationLevel,
out bool checkOverflow,
out string cryptoKeyContainer,
out string cryptoKeyFile,
out ImmutableArray<byte> cryptoPublicKey,
out bool? delaySign,
out Platform platform,
out ReportDiagnostic generalDiagnosticOption,
out int warningLevel,
out IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
out bool concurrentBuild,
out bool deterministic,
out bool publicSign,
out MetadataImportOptions metadataImportOptions,
out XmlReferenceResolver xmlReferenceResolver,
out SourceReferenceResolver sourceReferenceResolver,
out MetadataReferenceResolver metadataReferenceResolver,
out AssemblyIdentityComparer assemblyIdentityComparer,
out StrongNameProvider strongNameProvider,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
outputKind = (OutputKind)reader.ReadInt32();
reportSuppressedDiagnostics = reader.ReadBoolean();
moduleName = reader.ReadString();
mainTypeName = reader.ReadString();
scriptClassName = reader.ReadString();
optimizationLevel = (OptimizationLevel)reader.ReadInt32();
checkOverflow = reader.ReadBoolean();
// REVIEW: is it okay this being not part of snapshot?
cryptoKeyContainer = reader.ReadString();
cryptoKeyFile = reader.ReadString();
cryptoPublicKey = reader.ReadArray<byte>().ToImmutableArrayOrEmpty();
delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;
platform = (Platform)reader.ReadInt32();
generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();
warningLevel = reader.ReadInt32();
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
// not sure why CompilationOptions uses SequencialEqual to check options equality
// when ordering can change result of it even if contents are same.
var count = reader.ReadInt32();
List<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptionsList = null;
if (count > 0)
{
specificDiagnosticOptionsList = new List<KeyValuePair<string, ReportDiagnostic>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadString();
var value = (ReportDiagnostic)reader.ReadInt32();
specificDiagnosticOptionsList.Add(KeyValuePairUtil.Create(key, value));
}
}
specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, ReportDiagnostic>>();
concurrentBuild = reader.ReadBoolean();
deterministic = reader.ReadBoolean();
publicSign = reader.ReadBoolean();
metadataImportOptions = (MetadataImportOptions)reader.ReadByte();
// REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
// compiler.
xmlReferenceResolver = XmlFileResolver.Default;
sourceReferenceResolver = SourceFileResolver.Default;
metadataReferenceResolver = null;
assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
strongNameProvider = new DesktopStrongNameProvider();
}
protected static void WriteParseOptionsTo(ParseOptions options, ObjectWriter writer)
{
writer.WriteInt32((int)options.Kind);
writer.WriteInt32((int)options.DocumentationMode);
// REVIEW: I don't think there is a guarantee on ordering of elements in the readonly dictionary.
// unfortunately, we need to sort them to make it deterministic
writer.WriteInt32(options.Features.Count);
foreach (var kv in options.Features.OrderBy(o => o.Key))
{
writer.WriteString(kv.Key);
writer.WriteString(kv.Value);
}
}
protected static void ReadParseOptionsFrom(
ObjectReader reader,
out SourceCodeKind kind,
out DocumentationMode documentationMode,
out IEnumerable<KeyValuePair<string, string>> features,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
kind = (SourceCodeKind)reader.ReadInt32();
documentationMode = (DocumentationMode)reader.ReadInt32();
// REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
// unfortunately, we need to sort them to make it deterministic
// not sure why ParseOptions uses SequencialEqual to check options equality
// when ordering can change result of it even if contents are same.
var count = reader.ReadInt32();
List<KeyValuePair<string, string>> featuresList = null;
if (count > 0)
{
featuresList = new List<KeyValuePair<string, string>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadString();
var value = reader.ReadString();
featuresList.Add(KeyValuePairUtil.Create(key, value));
}
}
features = featuresList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, string>>();
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/Core/Portable/InternalUtilities/CommandLineUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
namespace Roslyn.Utilities
{
internal static class CommandLineUtilities
{
/// <summary>
/// Split a command line by the same rules as Main would get the commands except the original
/// state of backslashes and quotes are preserved. For example in normal Windows command line
/// parsing the following command lines would produce equivalent Main arguments:
///
/// - /r:a,b
/// - /r:"a,b"
///
/// This method will differ as the latter will have the quotes preserved. The only case where
/// quotes are removed is when the entire argument is surrounded by quotes without any inner
/// quotes.
/// </summary>
/// <remarks>
/// Rules for command line parsing, according to MSDN:
///
/// Arguments are delimited by white space, which is either a space or a tab.
///
/// A string surrounded by double quotation marks ("string") is interpreted
/// as a single argument, regardless of white space contained within.
/// A quoted string can be embedded in an argument.
///
/// A double quotation mark preceded by a backslash (\") is interpreted as a
/// literal double quotation mark character (").
///
/// Backslashes are interpreted literally, unless they immediately precede a
/// double quotation mark.
///
/// If an even number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is interpreted as a string delimiter.
///
/// If an odd number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is "escaped" by the remaining backslash,
/// causing a literal double quotation mark (") to be placed in argv.
/// </remarks>
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)
{
return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);
}
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)
{
var list = new List<string>();
SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);
return list;
}
public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar)
{
var i = 0;
builder.Length = 0;
illegalChar = null;
while (i < commandLine.Length)
{
while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))
{
i++;
}
if (i == commandLine.Length)
{
break;
}
if (commandLine[i] == '#' && removeHashComments)
{
break;
}
var quoteCount = 0;
builder.Length = 0;
while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))
{
var current = commandLine[i];
switch (current)
{
case '\\':
{
var slashCount = 0;
do
{
builder.Append(commandLine[i]);
i++;
slashCount++;
} while (i < commandLine.Length && commandLine[i] == '\\');
// Slashes not followed by a quote character can be ignored for now
if (i >= commandLine.Length || commandLine[i] != '"')
{
break;
}
// If there is an odd number of slashes then it is escaping the quote
// otherwise it is just a quote.
if (slashCount % 2 == 0)
{
quoteCount++;
}
builder.Append('"');
i++;
break;
}
case '"':
builder.Append(current);
quoteCount++;
i++;
break;
default:
if ((current >= 0x1 && current <= 0x1f) || current == '|')
{
if (illegalChar == null)
{
illegalChar = current;
}
}
else
{
builder.Append(current);
}
i++;
break;
}
}
// If the quote string is surrounded by quotes with no interior quotes then
// remove the quotes here.
if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"')
{
builder.Remove(0, length: 1);
builder.Remove(builder.Length - 1, length: 1);
}
if (builder.Length > 0)
{
list.Add(builder.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.
using System;
using System.Collections.Generic;
using System.Text;
namespace Roslyn.Utilities
{
internal static class CommandLineUtilities
{
/// <summary>
/// Split a command line by the same rules as Main would get the commands except the original
/// state of backslashes and quotes are preserved. For example in normal Windows command line
/// parsing the following command lines would produce equivalent Main arguments:
///
/// - /r:a,b
/// - /r:"a,b"
///
/// This method will differ as the latter will have the quotes preserved. The only case where
/// quotes are removed is when the entire argument is surrounded by quotes without any inner
/// quotes.
/// </summary>
/// <remarks>
/// Rules for command line parsing, according to MSDN:
///
/// Arguments are delimited by white space, which is either a space or a tab.
///
/// A string surrounded by double quotation marks ("string") is interpreted
/// as a single argument, regardless of white space contained within.
/// A quoted string can be embedded in an argument.
///
/// A double quotation mark preceded by a backslash (\") is interpreted as a
/// literal double quotation mark character (").
///
/// Backslashes are interpreted literally, unless they immediately precede a
/// double quotation mark.
///
/// If an even number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is interpreted as a string delimiter.
///
/// If an odd number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is "escaped" by the remaining backslash,
/// causing a literal double quotation mark (") to be placed in argv.
/// </remarks>
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)
{
return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);
}
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)
{
var list = new List<string>();
SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);
return list;
}
public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar)
{
var i = 0;
builder.Length = 0;
illegalChar = null;
while (i < commandLine.Length)
{
while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))
{
i++;
}
if (i == commandLine.Length)
{
break;
}
if (commandLine[i] == '#' && removeHashComments)
{
break;
}
var quoteCount = 0;
builder.Length = 0;
while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))
{
var current = commandLine[i];
switch (current)
{
case '\\':
{
var slashCount = 0;
do
{
builder.Append(commandLine[i]);
i++;
slashCount++;
} while (i < commandLine.Length && commandLine[i] == '\\');
// Slashes not followed by a quote character can be ignored for now
if (i >= commandLine.Length || commandLine[i] != '"')
{
break;
}
// If there is an odd number of slashes then it is escaping the quote
// otherwise it is just a quote.
if (slashCount % 2 == 0)
{
quoteCount++;
}
builder.Append('"');
i++;
break;
}
case '"':
builder.Append(current);
quoteCount++;
i++;
break;
default:
if ((current >= 0x1 && current <= 0x1f) || current == '|')
{
if (illegalChar == null)
{
illegalChar = current;
}
}
else
{
builder.Append(current);
}
i++;
break;
}
}
// If the quote string is surrounded by quotes with no interior quotes then
// remove the quotes here.
if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"')
{
builder.Remove(0, length: 1);
builder.Remove(builder.Length - 1, length: 1);
}
if (builder.Length > 0)
{
list.Add(builder.ToString());
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons_Constants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial struct InvocationReasons
{
public static readonly InvocationReasons DocumentAdded =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentAdded,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons DocumentRemoved =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentRemoved,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons ProjectParseOptionChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.ProjectParseOptionsChanged,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons ProjectConfigurationChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.ProjectConfigurationChanged,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons SolutionRemoved =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SolutionRemoved,
PredefinedInvocationReasons.DocumentRemoved));
public static readonly InvocationReasons DocumentOpened =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentOpened,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons DocumentClosed =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentClosed,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons DocumentChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons AdditionalDocumentChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons SyntaxChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged));
public static readonly InvocationReasons SemanticChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons Reanalyze =
new(PredefinedInvocationReasons.Reanalyze);
public static readonly InvocationReasons ReanalyzeHighPriority =
Reanalyze.With(PredefinedInvocationReasons.HighPriority);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial struct InvocationReasons
{
public static readonly InvocationReasons DocumentAdded =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentAdded,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons DocumentRemoved =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentRemoved,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons ProjectParseOptionChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.ProjectParseOptionsChanged,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons ProjectConfigurationChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.ProjectConfigurationChanged,
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons SolutionRemoved =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SolutionRemoved,
PredefinedInvocationReasons.DocumentRemoved));
public static readonly InvocationReasons DocumentOpened =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentOpened,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons DocumentClosed =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.DocumentClosed,
PredefinedInvocationReasons.HighPriority));
public static readonly InvocationReasons DocumentChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons AdditionalDocumentChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged,
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons SyntaxChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SyntaxChanged));
public static readonly InvocationReasons SemanticChanged =
new(
ImmutableHashSet.Create<string>(
PredefinedInvocationReasons.SemanticChanged));
public static readonly InvocationReasons Reanalyze =
new(PredefinedInvocationReasons.Reanalyze);
public static readonly InvocationReasons ReanalyzeHighPriority =
Reanalyze.With(PredefinedInvocationReasons.HighPriority);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentDocumentHighlightName)]
internal class DocumentHighlightsHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, DocumentHighlight[]>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentHighlightsHandler()
{
}
public override string Method => Methods.TextDocumentDocumentHighlightName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument;
public override async Task<DocumentHighlight[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return Array.Empty<DocumentHighlight>();
}
var documentHighlightService = document.Project.LanguageServices.GetRequiredService<IDocumentHighlightsService>();
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var highlights = await documentHighlightService.GetDocumentHighlightsAsync(
document,
position,
ImmutableHashSet.Create(document),
cancellationToken).ConfigureAwait(false);
if (!highlights.IsDefaultOrEmpty)
{
// LSP requests are only for a single document. So just get the highlights for the requested document.
var highlightsForDocument = highlights.FirstOrDefault(h => h.Document.Id == document.Id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
return highlightsForDocument.HighlightSpans.Select(h => new DocumentHighlight
{
Range = ProtocolConversions.TextSpanToRange(h.TextSpan, text),
Kind = ProtocolConversions.HighlightSpanKindToDocumentHighlightKind(h.Kind),
}).ToArray();
}
return Array.Empty<DocumentHighlight>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentDocumentHighlightName)]
internal class DocumentHighlightsHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, DocumentHighlight[]>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentHighlightsHandler()
{
}
public override string Method => Methods.TextDocumentDocumentHighlightName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument;
public override async Task<DocumentHighlight[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return Array.Empty<DocumentHighlight>();
}
var documentHighlightService = document.Project.LanguageServices.GetRequiredService<IDocumentHighlightsService>();
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var highlights = await documentHighlightService.GetDocumentHighlightsAsync(
document,
position,
ImmutableHashSet.Create(document),
cancellationToken).ConfigureAwait(false);
if (!highlights.IsDefaultOrEmpty)
{
// LSP requests are only for a single document. So just get the highlights for the requested document.
var highlightsForDocument = highlights.FirstOrDefault(h => h.Document.Id == document.Id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
return highlightsForDocument.HighlightSpans.Select(h => new DocumentHighlight
{
Range = ProtocolConversions.TextSpanToRange(h.TextSpan, text),
Kind = ProtocolConversions.HighlightSpanKindToDocumentHighlightKind(h.Kind),
}).ToArray();
}
return Array.Empty<DocumentHighlight>();
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TupleNameCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
public class TupleNameCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType() => typeof(TupleNameCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParen()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$)
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenInTupleExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$, zword: 2
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenInTupleExpressionWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$, zword: 2
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterComma()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, $$
}
}", "zword", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterCommaWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, $$)
}
}", "zword", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InTupleAsArgument()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main((int word, int zword) args)
{
Main(($$))
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiplePossibleTuples()
{
var markup = @"
class Program
{
static void Main((int number, int znumber) args) { }
static void Main((string word, int zword) args) {
Main(($$
}
}";
await VerifyItemExistsAsync(markup, "word", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "number", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiplePossibleTuplesAfterComma()
{
var markup = @"
class Program
{
static void Main((int number, int znumber) args) { }
static void Main((string word, int zword) args) {
Main((1, $$
}
}";
await VerifyItemExistsAsync(markup, "zword", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "znumber", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AtIndexGreaterThanNumberOfTupleElements()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, 2, 3, 4, $$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConvertCastToTupleExpression()
{
var markup = @"
class C
{
void goo()
{
(int goat, int moat) x = (g$$)1;
}
}";
await VerifyItemExistsAsync(markup, "goat", displayTextSuffix: ":");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
public class TupleNameCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType() => typeof(TupleNameCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParen()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$)
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenInTupleExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$, zword: 2
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOpenParenInTupleExpressionWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = ($$, zword: 2
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterComma()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, $$
}
}", "zword", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterCommaWithBraceCompletion()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, $$)
}
}", "zword", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InTupleAsArgument()
{
await VerifyItemExistsAsync(@"
class Program
{
static void Main((int word, int zword) args)
{
Main(($$))
}
}", "word", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiplePossibleTuples()
{
var markup = @"
class Program
{
static void Main((int number, int znumber) args) { }
static void Main((string word, int zword) args) {
Main(($$
}
}";
await VerifyItemExistsAsync(markup, "word", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "number", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiplePossibleTuplesAfterComma()
{
var markup = @"
class Program
{
static void Main((int number, int znumber) args) { }
static void Main((string word, int zword) args) {
Main((1, $$
}
}";
await VerifyItemExistsAsync(markup, "zword", displayTextSuffix: ":");
await VerifyItemExistsAsync(markup, "znumber", displayTextSuffix: ":");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AtIndexGreaterThanNumberOfTupleElements()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
(int word, int zword) t = (1, 2, 3, 4, $$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConvertCastToTupleExpression()
{
var markup = @"
class C
{
void goo()
{
(int goat, int moat) x = (g$$)1;
}
}";
await VerifyItemExistsAsync(markup, "goat", displayTextSuffix: ":");
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor_Minimal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
private bool TryAddAlias(
INamespaceOrTypeSymbol symbol,
ArrayBuilder<SymbolDisplayPart> builder)
{
var alias = GetAliasSymbol(symbol);
if (alias != null)
{
// We must verify that the alias actually binds back to the thing it's aliasing.
// It's possible there's another symbol with the same name as the alias that binds
// first
var aliasName = alias.Name;
var boundSymbols = semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name: aliasName);
if (boundSymbols.Length == 1)
{
var boundAlias = boundSymbols[0] as IAliasSymbol;
if ((object)boundAlias != null && alias.Target.Equals(symbol))
{
builder.Add(CreatePart(SymbolDisplayPartKind.AliasName, alias, aliasName));
return true;
}
}
}
return false;
}
protected override bool ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes()
{
var token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt);
var startNode = token.Parent;
return SyntaxFacts.IsInNamespaceOrTypeContext(startNode as ExpressionSyntax) || token.IsKind(SyntaxKind.NewKeyword) || this.inNamespaceOrType;
}
private void MinimallyQualify(INamespaceSymbol symbol)
{
// only the global namespace does not have a containing namespace
Debug.Assert(symbol.ContainingNamespace != null || symbol.IsGlobalNamespace);
// NOTE(cyrusn): We only call this once we've already checked if there is an alias that
// corresponds to this namespace.
if (symbol.IsGlobalNamespace)
{
// nothing to add for global namespace itself
return;
}
// Check if the name of this namespace binds to the same namespace symbol. If so,
// then that's all we need to add. Otherwise, we will add the minimally qualified
// version of our parent, and then add ourselves to that.
var symbols = ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes()
? semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name: symbol.Name)
: semanticModelOpt.LookupSymbols(positionOpt, name: symbol.Name);
var firstSymbol = symbols.OfType<ISymbol>().FirstOrDefault();
if (symbols.Length != 1 ||
firstSymbol == null ||
!firstSymbol.Equals(symbol))
{
// Just the name alone didn't bind properly. Add our minimally qualified parent (if
// we have one), a dot, and then our name.
var containingNamespace = symbol.ContainingNamespace == null
? null
: semanticModelOpt.Compilation.GetCompilationNamespace(symbol.ContainingNamespace);
if (containingNamespace != null)
{
if (containingNamespace.IsGlobalNamespace)
{
Debug.Assert(format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Included ||
format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Omitted ||
format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining);
if (format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Included)
{
AddGlobalNamespace(containingNamespace);
AddPunctuation(SyntaxKind.ColonColonToken);
}
}
else
{
containingNamespace.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
// If we bound properly, then we'll just add our name.
builder.Add(CreatePart(SymbolDisplayPartKind.NamespaceName, symbol, symbol.Name));
}
private void MinimallyQualify(INamedTypeSymbol symbol)
{
// NOTE(cyrusn): We only call this once we've already checked if there is an alias or
// special type that corresponds to this type.
//
// We first start by trying to bind just our name and type arguments. If they bind to
// the symbol that we were constructed from, then we have our minimal name. Otherwise,
// we get the minimal name of our parent, add a dot, and then add ourselves.
// TODO(cyrusn): This code needs to see if type is an attribute and if it can be shown
// in simplified form here.
if (!(symbol.IsAnonymousType || symbol.IsTupleType))
{
if (!NameBoundSuccessfullyToSameSymbol(symbol))
{
// Just the name alone didn't bind properly. Add our minimally qualified parent (if
// we have one), a dot, and then our name.
if (IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
else
{
var containingNamespace = symbol.ContainingNamespace == null
? null
: semanticModelOpt.Compilation.GetCompilationNamespace(symbol.ContainingNamespace);
if (containingNamespace != null)
{
if (containingNamespace.IsGlobalNamespace)
{
// Error symbols are put into the global namespace if the compiler has
// no better guess for it, so we shouldn't go spitting it everywhere.
if (symbol.TypeKind != TypeKind.Error)
{
AddKeyword(SyntaxKind.GlobalKeyword);
AddPunctuation(SyntaxKind.ColonColonToken);
}
}
else
{
containingNamespace.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
}
}
AddNameAndTypeArgumentsOrParameters(symbol);
}
private IDictionary<INamespaceOrTypeSymbol, IAliasSymbol> CreateAliasMap()
{
if (!this.IsMinimizing)
{
return SpecializedCollections.EmptyDictionary<INamespaceOrTypeSymbol, IAliasSymbol>();
}
// Walk up the ancestors from the current position. If this is a speculative
// model, walk up the corresponding ancestors in the parent model.
SemanticModel semanticModel;
int position;
if (semanticModelOpt.IsSpeculativeSemanticModel)
{
semanticModel = semanticModelOpt.ParentModel;
position = semanticModelOpt.OriginalPositionForSpeculation;
}
else
{
semanticModel = semanticModelOpt;
position = positionOpt;
}
var token = semanticModel.SyntaxTree.GetRoot().FindToken(position);
var startNode = token.Parent;
// NOTE(cyrusn): If we're currently in a block of usings, then we want to collect the
// aliases that are higher up than this block. Using aliases declared in a block of
// usings are not usable from within that same block.
var usingDirective = GetAncestorOrThis<UsingDirectiveSyntax>(startNode);
if (usingDirective != null)
{
startNode = usingDirective.Parent.Parent;
}
var usingAliases = GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>(startNode)
.SelectMany(n => n.Usings)
.Concat(GetAncestorsOrThis<CompilationUnitSyntax>(startNode).SelectMany(c => c.Usings))
.Where(u => u.Alias != null)
.Select(u => semanticModel.GetDeclaredSymbol(u) as IAliasSymbol)
.Where(u => u != null);
var builder = ImmutableDictionary.CreateBuilder<INamespaceOrTypeSymbol, IAliasSymbol>();
foreach (var alias in usingAliases)
{
if (!builder.ContainsKey(alias.Target))
{
builder.Add(alias.Target, alias);
}
}
return builder.ToImmutable();
}
private ITypeSymbol GetRangeVariableType(IRangeVariableSymbol symbol)
{
ITypeSymbol type = null;
if (this.IsMinimizing && !symbol.Locations.IsEmpty)
{
var location = symbol.Locations.First();
if (location.IsInSource && location.SourceTree == semanticModelOpt.SyntaxTree)
{
var token = location.SourceTree.GetRoot().FindToken(positionOpt);
var queryBody = GetQueryBody(token);
if (queryBody != null)
{
// To heuristically determine the type of the range variable in a query
// clause, we speculatively bind the name of the variable in the select
// or group clause of the query body.
var identifierName = SyntaxFactory.IdentifierName(symbol.Name);
type = semanticModelOpt.GetSpeculativeTypeInfo(
queryBody.SelectOrGroup.Span.End - 1, identifierName, SpeculativeBindingOption.BindAsExpression).Type;
}
var identifier = token.Parent as IdentifierNameSyntax;
if (identifier != null)
{
type = semanticModelOpt.GetTypeInfo(identifier).Type;
}
}
}
return type;
}
private static QueryBodySyntax GetQueryBody(SyntaxToken token) =>
token.Parent switch
{
FromClauseSyntax fromClause when fromClause.Identifier == token =>
fromClause.Parent as QueryBodySyntax ?? ((QueryExpressionSyntax)fromClause.Parent).Body,
LetClauseSyntax letClause when letClause.Identifier == token =>
letClause.Parent as QueryBodySyntax,
JoinClauseSyntax joinClause when joinClause.Identifier == token =>
joinClause.Parent as QueryBodySyntax,
QueryContinuationSyntax continuation when continuation.Identifier == token =>
continuation.Body,
_ => null
};
private string RemoveAttributeSufficeIfNecessary(INamedTypeSymbol symbol, string symbolName)
{
if (this.IsMinimizing &&
format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix) &&
semanticModelOpt.Compilation.IsAttributeType(symbol))
{
string nameWithoutAttributeSuffix;
if (symbolName.TryGetWithoutAttributeSuffix(out nameWithoutAttributeSuffix))
{
var token = SyntaxFactory.ParseToken(nameWithoutAttributeSuffix);
if (token.IsKind(SyntaxKind.IdentifierToken))
{
symbolName = nameWithoutAttributeSuffix;
}
}
}
return symbolName;
}
private static T GetAncestorOrThis<T>(SyntaxNode node) where T : SyntaxNode
{
return GetAncestorsOrThis<T>(node).FirstOrDefault();
}
private static IEnumerable<T> GetAncestorsOrThis<T>(SyntaxNode node) where T : SyntaxNode
{
return node == null
? SpecializedCollections.EmptyEnumerable<T>()
: node.AncestorsAndSelf().OfType<T>();
}
private IDictionary<INamespaceOrTypeSymbol, IAliasSymbol> AliasMap
{
get
{
var map = _lazyAliasMap;
if (map != null)
{
return map;
}
map = CreateAliasMap();
return Interlocked.CompareExchange(ref _lazyAliasMap, map, null) ?? map;
}
}
private IAliasSymbol GetAliasSymbol(INamespaceOrTypeSymbol symbol)
{
IAliasSymbol result;
return AliasMap.TryGetValue(symbol, out result) ? result : null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
private bool TryAddAlias(
INamespaceOrTypeSymbol symbol,
ArrayBuilder<SymbolDisplayPart> builder)
{
var alias = GetAliasSymbol(symbol);
if (alias != null)
{
// We must verify that the alias actually binds back to the thing it's aliasing.
// It's possible there's another symbol with the same name as the alias that binds
// first
var aliasName = alias.Name;
var boundSymbols = semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name: aliasName);
if (boundSymbols.Length == 1)
{
var boundAlias = boundSymbols[0] as IAliasSymbol;
if ((object)boundAlias != null && alias.Target.Equals(symbol))
{
builder.Add(CreatePart(SymbolDisplayPartKind.AliasName, alias, aliasName));
return true;
}
}
}
return false;
}
protected override bool ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes()
{
var token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt);
var startNode = token.Parent;
return SyntaxFacts.IsInNamespaceOrTypeContext(startNode as ExpressionSyntax) || token.IsKind(SyntaxKind.NewKeyword) || this.inNamespaceOrType;
}
private void MinimallyQualify(INamespaceSymbol symbol)
{
// only the global namespace does not have a containing namespace
Debug.Assert(symbol.ContainingNamespace != null || symbol.IsGlobalNamespace);
// NOTE(cyrusn): We only call this once we've already checked if there is an alias that
// corresponds to this namespace.
if (symbol.IsGlobalNamespace)
{
// nothing to add for global namespace itself
return;
}
// Check if the name of this namespace binds to the same namespace symbol. If so,
// then that's all we need to add. Otherwise, we will add the minimally qualified
// version of our parent, and then add ourselves to that.
var symbols = ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes()
? semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name: symbol.Name)
: semanticModelOpt.LookupSymbols(positionOpt, name: symbol.Name);
var firstSymbol = symbols.OfType<ISymbol>().FirstOrDefault();
if (symbols.Length != 1 ||
firstSymbol == null ||
!firstSymbol.Equals(symbol))
{
// Just the name alone didn't bind properly. Add our minimally qualified parent (if
// we have one), a dot, and then our name.
var containingNamespace = symbol.ContainingNamespace == null
? null
: semanticModelOpt.Compilation.GetCompilationNamespace(symbol.ContainingNamespace);
if (containingNamespace != null)
{
if (containingNamespace.IsGlobalNamespace)
{
Debug.Assert(format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Included ||
format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Omitted ||
format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining);
if (format.GlobalNamespaceStyle == SymbolDisplayGlobalNamespaceStyle.Included)
{
AddGlobalNamespace(containingNamespace);
AddPunctuation(SyntaxKind.ColonColonToken);
}
}
else
{
containingNamespace.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
// If we bound properly, then we'll just add our name.
builder.Add(CreatePart(SymbolDisplayPartKind.NamespaceName, symbol, symbol.Name));
}
private void MinimallyQualify(INamedTypeSymbol symbol)
{
// NOTE(cyrusn): We only call this once we've already checked if there is an alias or
// special type that corresponds to this type.
//
// We first start by trying to bind just our name and type arguments. If they bind to
// the symbol that we were constructed from, then we have our minimal name. Otherwise,
// we get the minimal name of our parent, add a dot, and then add ourselves.
// TODO(cyrusn): This code needs to see if type is an attribute and if it can be shown
// in simplified form here.
if (!(symbol.IsAnonymousType || symbol.IsTupleType))
{
if (!NameBoundSuccessfullyToSameSymbol(symbol))
{
// Just the name alone didn't bind properly. Add our minimally qualified parent (if
// we have one), a dot, and then our name.
if (IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
else
{
var containingNamespace = symbol.ContainingNamespace == null
? null
: semanticModelOpt.Compilation.GetCompilationNamespace(symbol.ContainingNamespace);
if (containingNamespace != null)
{
if (containingNamespace.IsGlobalNamespace)
{
// Error symbols are put into the global namespace if the compiler has
// no better guess for it, so we shouldn't go spitting it everywhere.
if (symbol.TypeKind != TypeKind.Error)
{
AddKeyword(SyntaxKind.GlobalKeyword);
AddPunctuation(SyntaxKind.ColonColonToken);
}
}
else
{
containingNamespace.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
}
}
AddNameAndTypeArgumentsOrParameters(symbol);
}
private IDictionary<INamespaceOrTypeSymbol, IAliasSymbol> CreateAliasMap()
{
if (!this.IsMinimizing)
{
return SpecializedCollections.EmptyDictionary<INamespaceOrTypeSymbol, IAliasSymbol>();
}
// Walk up the ancestors from the current position. If this is a speculative
// model, walk up the corresponding ancestors in the parent model.
SemanticModel semanticModel;
int position;
if (semanticModelOpt.IsSpeculativeSemanticModel)
{
semanticModel = semanticModelOpt.ParentModel;
position = semanticModelOpt.OriginalPositionForSpeculation;
}
else
{
semanticModel = semanticModelOpt;
position = positionOpt;
}
var token = semanticModel.SyntaxTree.GetRoot().FindToken(position);
var startNode = token.Parent;
// NOTE(cyrusn): If we're currently in a block of usings, then we want to collect the
// aliases that are higher up than this block. Using aliases declared in a block of
// usings are not usable from within that same block.
var usingDirective = GetAncestorOrThis<UsingDirectiveSyntax>(startNode);
if (usingDirective != null)
{
startNode = usingDirective.Parent.Parent;
}
var usingAliases = GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>(startNode)
.SelectMany(n => n.Usings)
.Concat(GetAncestorsOrThis<CompilationUnitSyntax>(startNode).SelectMany(c => c.Usings))
.Where(u => u.Alias != null)
.Select(u => semanticModel.GetDeclaredSymbol(u) as IAliasSymbol)
.Where(u => u != null);
var builder = ImmutableDictionary.CreateBuilder<INamespaceOrTypeSymbol, IAliasSymbol>();
foreach (var alias in usingAliases)
{
if (!builder.ContainsKey(alias.Target))
{
builder.Add(alias.Target, alias);
}
}
return builder.ToImmutable();
}
private ITypeSymbol GetRangeVariableType(IRangeVariableSymbol symbol)
{
ITypeSymbol type = null;
if (this.IsMinimizing && !symbol.Locations.IsEmpty)
{
var location = symbol.Locations.First();
if (location.IsInSource && location.SourceTree == semanticModelOpt.SyntaxTree)
{
var token = location.SourceTree.GetRoot().FindToken(positionOpt);
var queryBody = GetQueryBody(token);
if (queryBody != null)
{
// To heuristically determine the type of the range variable in a query
// clause, we speculatively bind the name of the variable in the select
// or group clause of the query body.
var identifierName = SyntaxFactory.IdentifierName(symbol.Name);
type = semanticModelOpt.GetSpeculativeTypeInfo(
queryBody.SelectOrGroup.Span.End - 1, identifierName, SpeculativeBindingOption.BindAsExpression).Type;
}
var identifier = token.Parent as IdentifierNameSyntax;
if (identifier != null)
{
type = semanticModelOpt.GetTypeInfo(identifier).Type;
}
}
}
return type;
}
private static QueryBodySyntax GetQueryBody(SyntaxToken token) =>
token.Parent switch
{
FromClauseSyntax fromClause when fromClause.Identifier == token =>
fromClause.Parent as QueryBodySyntax ?? ((QueryExpressionSyntax)fromClause.Parent).Body,
LetClauseSyntax letClause when letClause.Identifier == token =>
letClause.Parent as QueryBodySyntax,
JoinClauseSyntax joinClause when joinClause.Identifier == token =>
joinClause.Parent as QueryBodySyntax,
QueryContinuationSyntax continuation when continuation.Identifier == token =>
continuation.Body,
_ => null
};
private string RemoveAttributeSufficeIfNecessary(INamedTypeSymbol symbol, string symbolName)
{
if (this.IsMinimizing &&
format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix) &&
semanticModelOpt.Compilation.IsAttributeType(symbol))
{
string nameWithoutAttributeSuffix;
if (symbolName.TryGetWithoutAttributeSuffix(out nameWithoutAttributeSuffix))
{
var token = SyntaxFactory.ParseToken(nameWithoutAttributeSuffix);
if (token.IsKind(SyntaxKind.IdentifierToken))
{
symbolName = nameWithoutAttributeSuffix;
}
}
}
return symbolName;
}
private static T GetAncestorOrThis<T>(SyntaxNode node) where T : SyntaxNode
{
return GetAncestorsOrThis<T>(node).FirstOrDefault();
}
private static IEnumerable<T> GetAncestorsOrThis<T>(SyntaxNode node) where T : SyntaxNode
{
return node == null
? SpecializedCollections.EmptyEnumerable<T>()
: node.AncestorsAndSelf().OfType<T>();
}
private IDictionary<INamespaceOrTypeSymbol, IAliasSymbol> AliasMap
{
get
{
var map = _lazyAliasMap;
if (map != null)
{
return map;
}
map = CreateAliasMap();
return Interlocked.CompareExchange(ref _lazyAliasMap, map, null) ?? map;
}
}
private IAliasSymbol GetAliasSymbol(INamespaceOrTypeSymbol symbol)
{
IAliasSymbol result;
return AliasMap.TryGetValue(symbol, out result) ? result : null;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.ExecutableCodeBlockAnalyzerActions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct
{
[StructLayout(LayoutKind.Auto)]
private struct ExecutableCodeBlockAnalyzerActions
{
public DiagnosticAnalyzer Analyzer;
public ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> CodeBlockStartActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions;
public ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct
{
[StructLayout(LayoutKind.Auto)]
private struct ExecutableCodeBlockAnalyzerActions
{
public DiagnosticAnalyzer Analyzer;
public ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> CodeBlockStartActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions;
public ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs | // Licensed to the .NET Foundation under one or more 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.MoveToNamespace
{
internal abstract partial class AbstractMoveToNamespaceCodeAction
{
private class MoveTypeToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction
{
public override string Title => FeaturesResources.Move_to_namespace;
public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult)
: base(changeNamespaceService, analysisResult)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.MoveToNamespace
{
internal abstract partial class AbstractMoveToNamespaceCodeAction
{
private class MoveTypeToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction
{
public override string Title => FeaturesResources.Move_to_namespace;
public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult)
: base(changeNamespaceService, analysisResult)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrRuntimeInstance.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Core/Implementation/EditAndContinue/ManagedEditAndContinueLanguageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
[Shared]
[Export(typeof(IManagedEditAndContinueLanguageService))]
[ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)]
internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService
{
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource;
private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService;
private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider;
private RemoteDebuggingSessionProxy? _debuggingSession;
private bool _disabled;
/// <summary>
/// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them
/// unless it implements debugger components.
/// </summary>
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ManagedEditAndContinueLanguageService(
Lazy<IHostWorkspaceProvider> workspaceProvider,
Lazy<IManagedEditAndContinueDebuggerService> debuggerService,
IDiagnosticAnalyzerService diagnosticService,
EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource)
{
_workspaceProvider = workspaceProvider;
_debuggerService = debuggerService;
_diagnosticService = diagnosticService;
_diagnosticUpdateSource = diagnosticUpdateSource;
}
private Solution GetCurrentCompileTimeSolution()
{
var workspace = _workspaceProvider.Value.Workspace;
return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution);
}
private IDebuggingWorkspaceService GetDebuggingService()
=> _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>();
private IActiveStatementTrackingService GetActiveStatementTrackingService()
=> _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>();
private RemoteDebuggingSessionProxy GetDebuggingSession()
{
var debuggingSession = _debuggingSession;
Contract.ThrowIfNull(debuggingSession);
return debuggingSession;
}
/// <summary>
/// Called by the debugger when a debugging session starts and managed debugging is being used.
/// </summary>
public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0;
if (_disabled)
{
return;
}
try
{
var workspace = _workspaceProvider.Value.Workspace;
var solution = GetCurrentCompileTimeSolution();
var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray();
var proxy = new RemoteEditAndContinueServiceProxy(workspace);
_debuggingSession = await proxy.StartDebuggingSessionAsync(
solution,
_debuggerService.Value,
captureMatchingDocuments: openedDocumentIds,
captureAllMatchingDocuments: false,
reportDiagnostics: true,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
}
// the service failed, error has been reported - disable further operations
_disabled = _debuggingSession == null;
}
public async Task EnterBreakStateAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
if (_disabled)
{
return;
}
var solution = GetCurrentCompileTimeSolution();
var session = GetDebuggingSession();
try
{
await session.BreakStateEnteredAsync(_diagnosticService, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
_disabled = true;
return;
}
// Start tracking after we entered break state so that break-state session is active.
// This is potentially costly operation but entering break state is non-blocking so it should be ok to await.
await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false);
}
public Task ExitBreakStateAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
if (!_disabled)
{
GetActiveStatementTrackingService().EndTracking();
}
return Task.CompletedTask;
}
public async Task CommitUpdatesAsync(CancellationToken cancellationToken)
{
try
{
Contract.ThrowIfTrue(_disabled);
await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
public async Task DiscardUpdatesAsync(CancellationToken cancellationToken)
{
if (_disabled)
{
return;
}
try
{
await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
public async Task StopDebuggingAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
if (_disabled)
{
return;
}
try
{
var solution = GetCurrentCompileTimeSolution();
await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false);
_debuggingSession = null;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
_disabled = true;
}
}
private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution)
{
var service = GetActiveStatementTrackingService();
return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken));
}
/// <summary>
/// Returns true if any changes have been made to the source since the last changes had been applied.
/// </summary>
public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken)
{
try
{
var debuggingSession = _debuggingSession;
if (debuggingSession == null)
{
return false;
}
var solution = GetCurrentCompileTimeSolution();
var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution);
return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return true;
}
}
public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution);
var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false);
return updates;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
}
}
public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
var activeStatementTrackingService = GetActiveStatementTrackingService();
var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) =>
activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken));
var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false);
return span?.ToSourceSpan();
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return null;
}
}
public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
[Shared]
[Export(typeof(IManagedEditAndContinueLanguageService))]
[ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)]
internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService
{
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource;
private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService;
private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider;
private RemoteDebuggingSessionProxy? _debuggingSession;
private bool _disabled;
/// <summary>
/// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them
/// unless it implements debugger components.
/// </summary>
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ManagedEditAndContinueLanguageService(
Lazy<IHostWorkspaceProvider> workspaceProvider,
Lazy<IManagedEditAndContinueDebuggerService> debuggerService,
IDiagnosticAnalyzerService diagnosticService,
EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource)
{
_workspaceProvider = workspaceProvider;
_debuggerService = debuggerService;
_diagnosticService = diagnosticService;
_diagnosticUpdateSource = diagnosticUpdateSource;
}
private Solution GetCurrentCompileTimeSolution()
{
var workspace = _workspaceProvider.Value.Workspace;
return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution);
}
private IDebuggingWorkspaceService GetDebuggingService()
=> _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>();
private IActiveStatementTrackingService GetActiveStatementTrackingService()
=> _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>();
private RemoteDebuggingSessionProxy GetDebuggingSession()
{
var debuggingSession = _debuggingSession;
Contract.ThrowIfNull(debuggingSession);
return debuggingSession;
}
/// <summary>
/// Called by the debugger when a debugging session starts and managed debugging is being used.
/// </summary>
public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0;
if (_disabled)
{
return;
}
try
{
var workspace = _workspaceProvider.Value.Workspace;
var solution = GetCurrentCompileTimeSolution();
var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray();
var proxy = new RemoteEditAndContinueServiceProxy(workspace);
_debuggingSession = await proxy.StartDebuggingSessionAsync(
solution,
_debuggerService.Value,
captureMatchingDocuments: openedDocumentIds,
captureAllMatchingDocuments: false,
reportDiagnostics: true,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
}
// the service failed, error has been reported - disable further operations
_disabled = _debuggingSession == null;
}
public async Task EnterBreakStateAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
if (_disabled)
{
return;
}
var solution = GetCurrentCompileTimeSolution();
var session = GetDebuggingSession();
try
{
await session.BreakStateEnteredAsync(_diagnosticService, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
_disabled = true;
return;
}
// Start tracking after we entered break state so that break-state session is active.
// This is potentially costly operation but entering break state is non-blocking so it should be ok to await.
await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false);
}
public Task ExitBreakStateAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
if (!_disabled)
{
GetActiveStatementTrackingService().EndTracking();
}
return Task.CompletedTask;
}
public async Task CommitUpdatesAsync(CancellationToken cancellationToken)
{
try
{
Contract.ThrowIfTrue(_disabled);
await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
public async Task DiscardUpdatesAsync(CancellationToken cancellationToken)
{
if (_disabled)
{
return;
}
try
{
await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
}
}
public async Task StopDebuggingAsync(CancellationToken cancellationToken)
{
GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
if (_disabled)
{
return;
}
try
{
var solution = GetCurrentCompileTimeSolution();
await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false);
_debuggingSession = null;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
_disabled = true;
}
}
private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution)
{
var service = GetActiveStatementTrackingService();
return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken));
}
/// <summary>
/// Returns true if any changes have been made to the source since the last changes had been applied.
/// </summary>
public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken)
{
try
{
var debuggingSession = _debuggingSession;
if (debuggingSession == null)
{
return false;
}
var solution = GetCurrentCompileTimeSolution();
var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution);
return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return true;
}
}
public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution);
var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false);
return updates;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty);
}
}
public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
var activeStatementTrackingService = GetActiveStatementTrackingService();
var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) =>
activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken));
var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false);
return span?.ToSourceSpan();
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return null;
}
}
public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken)
{
try
{
var solution = GetCurrentCompileTimeSolution();
return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/Core/Test/SolutionExplorer/AnalyzerItemTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer
<[UseExportProvider]>
Public Class AnalyzerItemTests
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub Name()
Dim workspaceXml =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim project = workspace.Projects.Single()
Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing)
Dim analyzer = New AnalyzerItem(analyzerFolder, project.AnalyzerReferences.Single(), Nothing)
Assert.Equal(expected:="Goo", actual:=analyzer.Text)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub BrowseObject1()
Dim workspaceXml =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim project = workspace.Projects.Single()
Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing)
Dim analyzer = New AnalyzerItem(analyzerFolder, project.AnalyzerReferences.Single(), Nothing)
Dim browseObject = DirectCast(analyzer.GetBrowseObject(), AnalyzerItem.BrowseObject)
Assert.Equal(expected:=SolutionExplorerShim.Analyzer_Properties, actual:=browseObject.GetClassName())
Assert.Equal(expected:="Goo", actual:=browseObject.GetComponentName())
Assert.Equal(expected:="Goo", actual:=browseObject.Name)
Assert.Equal(expected:="C:\Users\Bill\Documents\Analyzers\Goo.dll", actual:=browseObject.Path)
End Using
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer
<[UseExportProvider]>
Public Class AnalyzerItemTests
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub Name()
Dim workspaceXml =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim project = workspace.Projects.Single()
Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing)
Dim analyzer = New AnalyzerItem(analyzerFolder, project.AnalyzerReferences.Single(), Nothing)
Assert.Equal(expected:="Goo", actual:=analyzer.Text)
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub BrowseObject1()
Dim workspaceXml =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml)
Dim project = workspace.Projects.Single()
Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing)
Dim analyzer = New AnalyzerItem(analyzerFolder, project.AnalyzerReferences.Single(), Nothing)
Dim browseObject = DirectCast(analyzer.GetBrowseObject(), AnalyzerItem.BrowseObject)
Assert.Equal(expected:=SolutionExplorerShim.Analyzer_Properties, actual:=browseObject.GetClassName())
Assert.Equal(expected:="Goo", actual:=browseObject.GetComponentName())
Assert.Equal(expected:="Goo", actual:=browseObject.Name)
Assert.Equal(expected:="C:\Users\Bill\Documents\Analyzers\Goo.dll", actual:=browseObject.Path)
End Using
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/VisualBasic/Portable/Binding/Binder_Conversions.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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' Binding of conversion operators is implemented in this part.
Partial Friend Class Binder
Private Function BindCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim result As BoundExpression
Select Case node.Keyword.Kind
Case SyntaxKind.CTypeKeyword
result = BindCTypeExpression(node, diagnostics)
Case SyntaxKind.DirectCastKeyword
result = BindDirectCastExpression(node, diagnostics)
Case SyntaxKind.TryCastKeyword
result = BindTryCastExpression(node, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return result
End Function
Private Function BindCTypeExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.CTypeKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyConversion(node, targetType, argument, isExplicit:=True, diagnostics)
End Function
Private Function BindDirectCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.DirectCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyDirectCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyDirectCastConversion(
node As SyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundDirectCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True)
End If
' Classify conversion
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If ReclassifyExpression(argument, SyntaxKind.DirectCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.DirectCast, "Associated wrong node with conversion?")
argument = New BoundDirectCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
If Conversions.IsIdentityConversion(conv) Then
If targetType.IsFloatingType() Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_IdentityDirectCastForFloat)
ElseIf targetType.IsValueType Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ObsoleteIdentityDirectCastForValueType)
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
Debug.Assert(Conversions.IsIdentityConversion(conv) OrElse
conv = ConversionKind.WideningNothingLiteral OrElse
sourceType.GetEnumUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(targetType.GetEnumUnderlyingTypeOrSelf()))
Debug.Assert(Not integerOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
End If
Return New BoundDirectCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindTryCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.TryCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyTryCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyTryCastConversion(
node As SyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundTryCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True)
End If
' Classify conversion
Dim conv As ConversionKind
If targetType.IsReferenceType Then
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
conv = Conversions.ClassifyTryCastConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
Else
conv = Nothing
End If
If ReclassifyExpression(argument, SyntaxKind.TryCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.TryCast, "Associated wrong node with conversion?")
argument = New BoundTryCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If targetType.IsValueType() Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfValueType1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
ElseIf targetType.IsTypeParameter() AndAlso Not targetType.IsReferenceType Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfUnconstrainedTypeParam1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
ElseIf sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
Return New BoundTryCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindPredefinedCastExpression(
node As PredefinedCastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetType As SpecialType
Select Case node.Keyword.Kind
Case SyntaxKind.CBoolKeyword : targetType = SpecialType.System_Boolean
Case SyntaxKind.CByteKeyword : targetType = SpecialType.System_Byte
Case SyntaxKind.CCharKeyword : targetType = SpecialType.System_Char
Case SyntaxKind.CDateKeyword : targetType = SpecialType.System_DateTime
Case SyntaxKind.CDecKeyword : targetType = SpecialType.System_Decimal
Case SyntaxKind.CDblKeyword : targetType = SpecialType.System_Double
Case SyntaxKind.CIntKeyword : targetType = SpecialType.System_Int32
Case SyntaxKind.CLngKeyword : targetType = SpecialType.System_Int64
Case SyntaxKind.CObjKeyword : targetType = SpecialType.System_Object
Case SyntaxKind.CSByteKeyword : targetType = SpecialType.System_SByte
Case SyntaxKind.CShortKeyword : targetType = SpecialType.System_Int16
Case SyntaxKind.CSngKeyword : targetType = SpecialType.System_Single
Case SyntaxKind.CStrKeyword : targetType = SpecialType.System_String
Case SyntaxKind.CUIntKeyword : targetType = SpecialType.System_UInt32
Case SyntaxKind.CULngKeyword : targetType = SpecialType.System_UInt64
Case SyntaxKind.CUShortKeyword : targetType = SpecialType.System_UInt16
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return ApplyConversion(node, GetSpecialType(targetType, node.Keyword, diagnostics),
BindValue(node.Expression, diagnostics),
isExplicit:=True, diagnostics:=diagnostics)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Friend Function ApplyImplicitConversion(
node As SyntaxNode,
targetType As TypeSymbol,
expression As BoundExpression,
diagnostics As BindingDiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False
) As BoundExpression
Return ApplyConversion(node, targetType, expression, False, diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of explicit or non-identity conversion.
''' </summary>
Private Function ApplyConversion(
node As SyntaxNode,
targetType As TypeSymbol,
argument As BoundExpression,
isExplicit As Boolean,
diagnostics As BindingDiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(node IsNot Nothing)
Debug.Assert(Not isOperandOfConditionalBranch OrElse Not isExplicit)
Debug.Assert(argument.IsValue())
' Deal with erroneous arguments
If targetType.IsErrorType Then
argument = MakeRValueAndIgnoreDiagnostics(argument)
If Not isExplicit AndAlso argument.Type.IsSameTypeIgnoringAll(targetType) Then
Return argument
End If
Return New BoundConversion(node,
argument,
conversionKind:=Nothing,
checked:=CheckOverflow,
explicitCastInCode:=isExplicit,
type:=targetType,
hasErrors:=True)
End If
If argument.HasErrors Then
' Suppress any additional diagnostics produced by this function
diagnostics = BindingDiagnosticBag.Discarded
End If
' Classify conversion
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol)
Dim applyNullableIsTrueOperator As Boolean = False
Dim isTrueOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim result As BoundExpression
Debug.Assert(Not isOperandOfConditionalBranch OrElse targetType.IsBooleanType())
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If isOperandOfConditionalBranch AndAlso targetType.IsBooleanType() Then
Debug.Assert(Not isExplicit)
conv = Conversions.ClassifyConversionOfOperandOfConditionalBranch(argument, targetType, Me,
applyNullableIsTrueOperator,
isTrueOperator,
useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If isTrueOperator.BestResult.HasValue Then
' Apply IsTrue operator.
Dim isTrue As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, UnaryOperatorKind.IsTrue, argument, isTrueOperator, diagnostics)
isTrue.SetWasCompilerGenerated()
isTrue.UnderlyingExpression.SetWasCompilerGenerated()
result = isTrue
Else
Dim intermediateTargetType As TypeSymbol
If applyNullableIsTrueOperator Then
' Note, use site error will be reported by ApplyNullableIsTrueOperator later.
Dim nullableOfT As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Nullable_T)
intermediateTargetType = Compilation.GetSpecialType(SpecialType.System_Nullable_T).
Construct(ImmutableArray.Create(Of TypeSymbol)(targetType))
Else
intermediateTargetType = targetType
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, intermediateTargetType, diagnostics)
End If
If applyNullableIsTrueOperator Then
result = Binder.ApplyNullableIsTrueOperator(result, targetType)
End If
Else
conv = Conversions.ClassifyConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, targetType, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
End If
Return result
End Function
Private Shared Function ApplyNullableIsTrueOperator(argument As BoundExpression, booleanType As TypeSymbol) As BoundNullableIsTrueOperator
Debug.Assert(argument.Type.IsNullableOfBoolean() AndAlso booleanType.IsBooleanType())
Return New BoundNullableIsTrueOperator(argument.Syntax, argument, booleanType).MakeCompilerGenerated()
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Private Function CreateConversionAndReportDiagnostic(
tree As SyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
Optional copybackConversionParamName As String = Nothing,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(argument.IsValue())
' We need to preserve any conversion that was explicitly written in code
' (so that GetSemanticInfo can find the syntax in the bound tree). Implicit identity conversion
' don't need representation in the bound tree (they would be optimized away in emit, but are so common
' that this is an important way to save both time and memory).
If (Not isExplicit OrElse explicitSemanticForConcatArgument) AndAlso Conversions.IsIdentityConversion(convKind.Key) Then
Debug.Assert(argument.Type.IsSameTypeIgnoringAll(targetType))
Debug.Assert(tree Is argument.Syntax)
Return MakeRValue(argument, diagnostics)
End If
If (convKind.Key And ConversionKind.UserDefined) = 0 AndAlso
ReclassifyExpression(argument, SyntaxKind.CTypeKeyword, tree, convKind.Key, isExplicit, targetType, diagnostics) Then
argument = MakeRValue(argument, diagnostics)
If isExplicit AndAlso argument.Syntax IsNot tree Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
argument = New BoundConversion(tree, argument, ConversionKind.Identity, CheckOverflow, isExplicit, targetType)
End If
Return argument
ElseIf Not argument.IsNothingLiteral() AndAlso argument.Kind <> BoundKind.ArrayLiteral Then
argument = MakeRValue(argument, diagnostics)
End If
Debug.Assert(argument.Kind <> BoundKind.Conversion OrElse DirectCast(argument, BoundConversion).ExplicitCastInCode OrElse
Not argument.IsNothingLiteral() OrElse
TypeOf argument.Syntax.Parent Is BinaryExpressionSyntax OrElse
TypeOf argument.Syntax.Parent Is UnaryExpressionSyntax OrElse
TypeOf argument.Syntax.Parent Is TupleExpressionSyntax OrElse
(TypeOf argument.Syntax.Parent Is AssignmentStatementSyntax AndAlso argument.Syntax.Parent.Kind <> SyntaxKind.SimpleAssignmentStatement),
"Applying yet another conversion to an implicit conversion from NOTHING, probably MakeRValue was called too early.")
Dim sourceType = argument.Type
' At this point if the expression is an array literal then the conversion must be user defined.
Debug.Assert(argument.Kind <> BoundKind.ArrayLiteral OrElse (convKind.Key And ConversionKind.UserDefined) <> 0)
Dim reportArrayLiteralElementNarrowingConversion = False
If argument.Kind = BoundKind.ArrayLiteral Then
' The array will get the type from the input type of the user defined conversion.
sourceType = convKind.Value.Parameters(0).Type
' If the conversion from the inferred element type to the source type of the user defined conversion is a narrowing conversion then
' skip to the user defined conversion. Conversion errors on the individual elements will be reported when the array literal is reclassified.
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
reportArrayLiteralElementNarrowingConversion =
Not isExplicit AndAlso
Conversions.IsNarrowingConversion(convKind.Key) AndAlso
Conversions.IsNarrowingConversion(Conversions.ClassifyArrayLiteralConversion(DirectCast(argument, BoundArrayLiteral), sourceType, Me, useSiteInfo))
diagnostics.Add(argument.Syntax, useSiteInfo)
If reportArrayLiteralElementNarrowingConversion Then
GoTo DoneWithDiagnostics
End If
End If
If argument.HasErrors Then
GoTo DoneWithDiagnostics
End If
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
GoTo DoneWithDiagnostics
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(convKind.Key) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics)
' Deal with implicit narrowing conversions
If Not isExplicit AndAlso Conversions.IsNarrowingConversion(convKind.Key) AndAlso
(convKind.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If copybackConversionParamName IsNot Nothing Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_StrictArgumentCopyBackNarrowing3,
copybackConversionParamName, sourceType, targetType)
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ImplicitConversionCopyBack,
copybackConversionParamName, sourceType, targetType)
End If
Else
' We have a narrowing conversion. This is how we might display it, depending on context:
' ERR_NarrowingConversionDisallowed2 "Option Strict On disallows implicit conversions from '|1' to '|2'."
' ERR_NarrowingConversionCollection2 "Option Strict On disallows implicit conversions from '|1' to '|2';
' the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type."
' ERR_AmbiguousCastConversion2 "Option Strict On disallows implicit conversions from '|1' to '|2' because the conversion is ambiguous."
' The Collection error is for when one type is Microsoft.VisualBasic.Collection and
' the other type is named _Collection.
' The Ambiguous error is for when the conversion was classed as "Narrowing" for reasons of ambiguity.
If OptionStrict = VisualBasic.OptionStrict.On Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
Dim err As ERRID = ERRID.ERR_NarrowingConversionDisallowed2
Const _Collection As String = "_Collection"
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
err = ERRID.ERR_AmbiguousCastConversion2
ElseIf (sourceType.IsMicrosoftVisualBasicCollection() AndAlso String.Equals(targetType.Name, _Collection, StringComparison.Ordinal)) OrElse
(String.Equals(sourceType.Name, _Collection, StringComparison.Ordinal) AndAlso targetType.IsMicrosoftVisualBasicCollection()) Then
' Got both, so use the more specific error message
err = ERRID.ERR_NarrowingConversionCollection2
End If
ReportDiagnostic(diagnostics, argument.Syntax, err, sourceType, targetType)
End If
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
' Avoid reporting a warning if narrowing caused exclusively by "zero argument" relaxation
' for an Anonymous Delegate. Note, that dropping a return is widening.
If (convKind.Key And ConversionKind.AnonymousDelegate) = 0 OrElse
(convKind.Key And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=True) Then
Dim wrnId1 As ERRID = ERRID.WRN_ImplicitConversionSubst1
Dim wrnId2 As ERRID = ERRID.WRN_ImplicitConversion2
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
wrnId2 = ERRID.WRN_AmbiguousCastConversion2
End If
ReportDiagnostic(diagnostics, argument.Syntax, wrnId1, ErrorFactory.ErrorInfo(wrnId2, sourceType, targetType))
End If
End If
End If
End If
End If
If Conversions.NoConversion(convKind.Key) Then
If Conversions.FailedDueToNumericOverflow(convKind.Key) Then
Dim errorTargetType As TypeSymbol
If (convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing Then
errorTargetType = convKind.Value.Parameters(0).Type
Else
errorTargetType = targetType
End If
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ExpressionOverflow1, errorTargetType)
ElseIf isExplicit OrElse Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics, copybackConversionParamName)
End If
Return New BoundConversion(tree, argument, convKind.Key And (Not ConversionKind.UserDefined), CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
DoneWithDiagnostics:
If (convKind.Key And ConversionKind.UserDefined) <> 0 Then
Return CreateUserDefinedConversion(tree, argument, convKind, isExplicit, targetType, reportArrayLiteralElementNarrowingConversion, diagnostics)
End If
If argument.HasErrors OrElse (sourceType IsNot Nothing AndAlso sourceType.IsErrorType()) Then
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
Return CreatePredefinedConversion(tree, argument, convKind.Key, isExplicit, targetType, diagnostics)
End Function
Private Structure VarianceSuggestionTypeParameterInfo
Private _isViable As Boolean
Private _typeParameter As TypeParameterSymbol
Private _derivedArgument As TypeSymbol
Private _baseArgument As TypeSymbol
Public Sub [Set](parameter As TypeParameterSymbol, derived As TypeSymbol, base As TypeSymbol)
_typeParameter = parameter
_derivedArgument = derived
_baseArgument = base
_isViable = True
End Sub
Public ReadOnly Property IsViable As Boolean
Get
Return _isViable
End Get
End Property
Public ReadOnly Property TypeParameter As TypeParameterSymbol
Get
Return _typeParameter
End Get
End Property
Public ReadOnly Property DerivedArgument As TypeSymbol
Get
Return _derivedArgument
End Get
End Property
Public ReadOnly Property BaseArgument As TypeSymbol
Get
Return _baseArgument
End Get
End Property
End Structure
''' <summary>
''' Returns True if error or warning was reported.
'''
''' This function is invoked on the occasion of a Narrowing or NoConversion.
''' It looks at the conversion. If the conversion could have been helped by variance in
''' some way, it reports an error/warning message to that effect and returns true. This
''' message is a substitute for whatever other conversion-failed message might have been displayed.
'''
''' Note: these variance-related messages will NOT show auto-correct suggestion of using CType. That's
''' because, in these cases, it's more likely than not that CType will fail, so it would be a bad suggestion
''' </summary>
Private Function MakeVarianceConversionSuggestion(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
justWarn As Boolean
) As Boolean
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim result As Boolean = MakeVarianceConversionSuggestion(convKind, location, sourceType, targetType, diagnostics, useSiteInfo, justWarn)
diagnostics.AddDependencies(useSiteInfo)
Return result
End Function
Private Function MakeVarianceConversionSuggestion(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
justWarn As Boolean
) As Boolean
If (convKind And ConversionKind.UserDefined) <> 0 Then
Return False
End If
' Variance scenario 2: Dim x As List(Of Animal) = New List(Of Tiger)
' "List(Of Tiger) cannot be converted to List(Of Animal). Consider using IEnumerable(Of Animal) instead."
'
' (1) If the user attempts a conversion to DEST which is a generic binding of one of the non-variant
' standard generic collection types List(Of D), Collection(Of D), ReadOnlyCollection(Of D),
' IList(Of D), ICollection(Of D)
' (2) and if the conversion failed (either ConversionNarrowing or ConversionError),
' (3) and if the source type SOURCE implemented/inherited exactly one binding ISOURCE=G(Of S) of that
' generic collection type G
' (4) and if there is a reference conversion from S to D
' (5) Then report "G(Of S) cannot be converted to G(Of D). Consider converting to IEnumerable(Of D) instead."
If targetType.Kind <> SymbolKind.NamedType Then
Return False
End If
Dim targetNamedType = DirectCast(targetType, NamedTypeSymbol)
If Not targetNamedType.IsGenericType Then
Return False
End If
Dim targetGenericDefinition As NamedTypeSymbol = targetNamedType.OriginalDefinition
If targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_List_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_Collection_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T) Then
Dim sourceTypeArgument As TypeSymbol = Nothing
If targetGenericDefinition.IsInterfaceType() Then
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteInfo:=useSiteInfo, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
sourceTypeArgument = matchingInterfaces(0).TypeArgumentsNoUseSiteDiagnostics(0)
End If
Else
Dim typeToCheck As TypeSymbol = sourceType
Do
If typeToCheck.OriginalDefinition Is targetGenericDefinition Then
sourceTypeArgument = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
Exit Do
End If
typeToCheck = typeToCheck.BaseTypeNoUseSiteDiagnostics
Loop While typeToCheck IsNot Nothing
End If
If sourceTypeArgument IsNot Nothing AndAlso
Conversions.IsWideningConversion(Conversions.Classify_Reference_Array_TypeParameterConversion(sourceTypeArgument,
targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0),
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)) Then
Dim iEnumerable_T As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
If Not iEnumerable_T.IsErrorType() Then
Dim suggestion As NamedTypeSymbol = iEnumerable_T.Construct(targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0))
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(ERRID.WRN_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion))
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion)
End If
Return True
End If
End If
End If
' Variance scenario 1: | Variance scenario 3:
' Dim x as IEnumerable(Of Tiger) = New List(Of Animal) | Dim x As IGoo(Of Animal) = New MyGoo
' "List(Of Animal) cannot be converted to | "MyGoo cannot be converted to IGoo(Of Animal).
' IEnumerable(Of Tiger) because 'Animal' is not derived | Consider changing the 'T' in the definition
' from 'Tiger', as required for the 'Out' generic | of interface IGoo(Of T) to an Out type
' parameter 'T' in 'IEnumerable(Of Out T)'" | parameter, Out T."
' |
' (1) If the user attempts a conversion to | (1) If the user attempts a conversion to some
' some target type DEST=G(Of D1,D2,...) which is | target type DEST=G(Of D1,D2,...) which is
' a generic instantiation of some variant interface/| a generic instantiation of some interface/delegate
' delegate type G(Of T1,T2,...), | type G(...), which NEED NOT be variant!
' (2) and if the conversion fails (Narrowing/Error), | (2) and if the type G is defined in source-code,
' (3) and if the source type SOURCE implements/ | not imported metadata. And the conversion fails.
' inherits exactly one binding INHSOURCE= | (3) And INHSOURCE=exactly one binding of G
' G(Of S1,S2,...) of that generic type G, | (4) And if ever difference is either Di/Si/Ti
' (4) and if the only differences between (D1,D2,...) | where Ti has In/Out variance, or is
' and (S1,S2,...) occur in positions "Di/Si" | Dj/Sj/Tj such that Tj has no variance and
' such that the corresponding Ti has either In | Dj has a CLR conversion to Sj or vice versa
' or Out variance | (5) Then pick the first difference Dj/Sj
' (5) Then pick on the one such difference Si/Di/Ti | (6) and report "SOURCE cannot be converted to
' (6) and report "SOURCE cannot be converted to DEST | DEST. Consider changing Tj in the definition
' because Si is not derived from Di, as required | of interface/delegate IGoo(Of T) to an
' for the 'In/Out' generic parameter 'T' in | In/Out type parameter, In/Out T".
' 'IEnumerable(Of Out T)'" |
Dim matchingGenericInstantiation As NamedTypeSymbol
' (1) If the user attempts a conversion
Select Case targetGenericDefinition.TypeKind
Case TypeKind.Delegate
If sourceType.OriginalDefinition Is targetGenericDefinition Then
matchingGenericInstantiation = DirectCast(sourceType, NamedTypeSymbol)
Else
Return False
End If
Case TypeKind.Interface
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteInfo:=useSiteInfo, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
matchingGenericInstantiation = matchingInterfaces(0)
Else
Return False
End If
Case Else
Return False
End Select
' (3) and if the source type implemented exactly one binding of it...
Dim source As NamedTypeSymbol = matchingGenericInstantiation
Dim destination As NamedTypeSymbol = targetNamedType
Dim oneVariantDifference As VarianceSuggestionTypeParameterInfo = Nothing ' for Di/Si/Ti
Dim oneInvariantConvertibleDifference As TypeParameterSymbol = Nothing 'for Dj/Sj/Tj where Sj<Dj
Dim oneInvariantReverseConvertibleDifference As TypeParameterSymbol = Nothing ' Dj/Sj/Tj where Dj<Sj
Do
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol) = source.TypeParameters
Dim sourceArguments As ImmutableArray(Of TypeSymbol) = source.TypeArgumentsNoUseSiteDiagnostics
Dim destinationArguments As ImmutableArray(Of TypeSymbol) = destination.TypeArgumentsNoUseSiteDiagnostics
For i As Integer = 0 To typeParameters.Length - 1
Dim sourceArg As TypeSymbol = sourceArguments(i)
Dim destinationArg As TypeSymbol = destinationArguments(i)
If sourceArg.IsSameTypeIgnoringAll(destinationArg) Then
Continue For
End If
If sourceArg.IsErrorType() OrElse destinationArg.IsErrorType() Then
Continue For
End If
Dim conv As ConversionKind = Nothing
Select Case typeParameters(i).Variance
Case VarianceKind.Out
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(sourceArg, destinationArg,
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)
If Not Conversions.IsWideningConversion(conv) Then
If Not Conversions.IsNarrowingConversion(conv) OrElse (conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
End If
End If
End If
Case VarianceKind.In
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(destinationArg, sourceArg,
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)
If Not Conversions.IsWideningConversion(conv) Then
If (targetNamedType.IsDelegateType AndAlso destinationArg.IsReferenceType AndAlso sourceArg.IsReferenceType) OrElse
Not Conversions.IsNarrowingConversion(conv) OrElse
(conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
End If
End If
End If
Case Else
conv = Conversions.ClassifyDirectCastConversion(sourceArg, destinationArg, useSiteInfo)
If Conversions.IsWideningConversion(conv) Then
oneInvariantConvertibleDifference = typeParameters(i)
Else
conv = Conversions.ClassifyDirectCastConversion(destinationArg, sourceArg, useSiteInfo)
If Conversions.IsWideningConversion(conv) Then
oneInvariantReverseConvertibleDifference = typeParameters(i)
Else
Return False
End If
End If
End Select
Next
source = source.ContainingType
destination = destination.ContainingType
Loop While source IsNot Nothing
' (5) If a Di/Si/Ti, and no Dj/Sj/Tj nor Dk/Sk/Tk, then report...
If oneVariantDifference.IsViable AndAlso
oneInvariantConvertibleDifference Is Nothing AndAlso
oneInvariantReverseConvertibleDifference Is Nothing Then
Dim containerFormatter As FormattedSymbol
If oneVariantDifference.TypeParameter.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneVariantDifference.TypeParameter.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneVariantDifference.TypeParameter.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.WRN_VarianceConversionFailedOut6,
ERRID.WRN_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType))
Else
ReportDiagnostic(diagnostics, location, If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.ERR_VarianceConversionFailedOut6,
ERRID.ERR_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType)
End If
Return True
End If
' (5b) Otherwise, if a Dj/Sj/Tj and no Dk/Sk/Tk, and G came not from metadata, then report...
If (oneInvariantConvertibleDifference IsNot Nothing OrElse oneInvariantReverseConvertibleDifference IsNot Nothing) AndAlso
targetType.ContainingModule Is Compilation.SourceModule Then
Dim oneInvariantDifference As TypeParameterSymbol
If oneInvariantConvertibleDifference IsNot Nothing Then
oneInvariantDifference = oneInvariantConvertibleDifference
Else
oneInvariantDifference = oneInvariantReverseConvertibleDifference
End If
Dim containerFormatter As FormattedSymbol
If oneInvariantDifference.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneInvariantDifference.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneInvariantDifference.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.WRN_VarianceConversionFailedTryOut4,
ERRID.WRN_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter))
Else
ReportDiagnostic(diagnostics, location, If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.ERR_VarianceConversionFailedTryOut4,
ERRID.ERR_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter)
End If
Return True
End If
Return False
End Function
Private Function CreatePredefinedConversion(
tree As SyntaxNode,
argument As BoundExpression,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundConversion
Debug.Assert(Conversions.ConversionExists(convKind) AndAlso (convKind And ConversionKind.UserDefined) = 0)
Dim sourceType = argument.Type
' Handle Anonymous Delegate conversion.
If (convKind And ConversionKind.AnonymousDelegate) <> 0 Then
' Don't spend time building a narrowing relaxation stub if we already complained about the narrowing.
If isExplicit OrElse OptionStrict <> VisualBasic.OptionStrict.On OrElse Conversions.IsWideningConversion(convKind) Then
Debug.Assert(Not Conversions.IsIdentityConversion(convKind))
Debug.Assert(sourceType.IsDelegateType() AndAlso DirectCast(sourceType, NamedTypeSymbol).IsAnonymousType AndAlso targetType.IsDelegateType() AndAlso
targetType.SpecialType <> SpecialType.System_MulticastDelegate)
Dim boundLambdaOpt As BoundLambda = Nothing
Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = Nothing
Dim methodToConvert As MethodSymbol = DirectCast(sourceType, NamedTypeSymbol).DelegateInvokeMethod
If (convKind And ConversionKind.NeedAStub) <> 0 Then
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
boundLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(tree, tree, argument, methodToConvert,
Nothing, QualificationKind.QualifiedViaValue,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
convKind And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=False,
diagnostics:=diagnostics,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholderOpt)
End If
' The conversion has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later the node get's rewritten into a delegate creation with the lambda if needed.
Return New BoundConversion(tree, argument, convKind, False, isExplicit, Nothing,
If(boundLambdaOpt Is Nothing,
Nothing,
New BoundRelaxationLambda(tree, boundLambdaOpt, relaxationReceiverPlaceholderOpt).MakeCompilerGenerated()),
targetType)
Else
Debug.Assert(Not diagnostics.AccumulatesDiagnostics OrElse diagnostics.HasAnyErrors())
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
' Overflow should have been detected at classification time.
Debug.Assert(Not integerOverflow OrElse Not CheckOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, convKind, targetType)
End If
Dim tupleElements As BoundConvertedTupleElements = CreateConversionForTupleElements(tree, sourceType, targetType, convKind, isExplicit)
Return New BoundConversion(tree, argument, convKind, CheckOverflow, isExplicit, constantResult, tupleElements, targetType)
End Function
Private Function CreateConversionForTupleElements(
tree As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
convKind As ConversionKind,
isExplicit As Boolean
) As BoundConvertedTupleElements
If (convKind And ConversionKind.Tuple) <> 0 Then
Dim sourceElementTypes = sourceType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible()
Dim targetElementTypes = targetType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible()
Dim placeholders = ArrayBuilder(Of BoundRValuePlaceholder).GetInstance(sourceElementTypes.Length)
Dim converted = ArrayBuilder(Of BoundExpression).GetInstance(sourceElementTypes.Length)
For i As Integer = 0 To sourceElementTypes.Length - 1
Dim placeholder = New BoundRValuePlaceholder(tree, sourceElementTypes(i)).MakeCompilerGenerated()
placeholders.Add(placeholder)
converted.Add(ApplyConversion(tree, targetElementTypes(i), placeholder, isExplicit, BindingDiagnosticBag.Discarded))
Next
Return New BoundConvertedTupleElements(tree, placeholders.ToImmutableAndFree(), converted.ToImmutableAndFree()).MakeCompilerGenerated()
End If
Return Nothing
End Function
Private Function CreateUserDefinedConversion(
tree As SyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
reportArrayLiteralElementNarrowingConversion As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundConversion
Debug.Assert((convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing AndAlso
convKind.Value.ParameterCount = 1 AndAlso Not convKind.Value.IsSub AndAlso
Not convKind.Value.Parameters(0).IsByRef AndAlso convKind.Value.IsShared)
' Suppress any Option Strict diagnostics.
Dim conversionBinder = New OptionStrictOffBinder(Me)
Dim argumentSyntax = argument.Syntax
Dim originalArgumentType As TypeSymbol = argument.Type
Dim inType As TypeSymbol = convKind.Value.Parameters(0).Type
Dim outType As TypeSymbol = convKind.Value.ReturnType
Dim intermediateConv As ConversionKind
Dim inOutConversionFlags As Byte = 0
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If argument.Kind = BoundKind.ArrayLiteral Then
' For array literals, report Option Strict diagnostics for each element when reportArrayLiteralElementNarrowingConversion is true.
Dim arrayLiteral = DirectCast(argument, BoundArrayLiteral)
Dim arrayLiteralBinder = If(reportArrayLiteralElementNarrowingConversion, Me, conversionBinder)
intermediateConv = Conversions.ClassifyArrayLiteralConversion(arrayLiteral, inType, arrayLiteralBinder, useSiteInfo)
argument = arrayLiteralBinder.ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, tree,
intermediateConv,
isExplicit,
arrayLiteral,
inType, diagnostics)
originalArgumentType = inType
Else
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, inType, conversionBinder, useSiteInfo)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, inType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = 1
End If
End If
ReportUseSite(diagnostics, tree, convKind.Value)
ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, convKind.Value, tree)
Debug.Assert(convKind.Value.IsUserDefinedOperator())
If Me.ContainingMember Is convKind.Value Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.WRN_RecursiveOperatorCall, convKind.Value)
End If
argument = New BoundCall(tree,
method:=convKind.Value,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray.Create(Of BoundExpression)(argument),
constantValueOpt:=Nothing,
suppressObjectClone:=True,
type:=outType).MakeCompilerGenerated()
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, targetType, conversionBinder, useSiteInfo)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, targetType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = inOutConversionFlags Or CByte(2)
End If
argument = New BoundUserDefinedConversion(tree, argument, inOutConversionFlags, originalArgumentType).MakeCompilerGenerated()
diagnostics.Add(tree, useSiteInfo)
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, DirectCast(Nothing, ConstantValue), targetType)
End Function
''' <summary>
''' Handle expression reclassification, if any applicable.
'''
''' If function returns True, the "argument" parameter has been replaced
''' with result of reclassification (possibly an error node) and appropriate
''' diagnostic, if any, has been reported.
'''
''' If function returns false, the "argument" parameter must be unchanged and no
''' diagnostic should be reported.
'''
''' conversionSemantics can be one of these:
''' SyntaxKind.CTypeKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.TryCastKeyword
''' </summary>
Private Function ReclassifyExpression(
ByRef argument As BoundExpression,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.GroupTypeInferenceLambda)
Select Case argument.Kind
Case BoundKind.Parenthesized
If argument.Type Is Nothing AndAlso Not argument.IsNothingLiteral() Then
Dim parenthesized = DirectCast(argument, BoundParenthesized)
Dim enclosed As BoundExpression = parenthesized.Expression
' Reclassify enclosed expression.
If ReclassifyExpression(enclosed, conversionSemantics, enclosed.Syntax, convKind, isExplicit, targetType, diagnostics) Then
argument = parenthesized.Update(enclosed, enclosed.Type)
Return True
End If
End If
Case BoundKind.UnboundLambda
argument = ReclassifyUnboundLambdaExpression(DirectCast(argument, UnboundLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.QueryLambda
argument = ReclassifyQueryLambdaExpression(DirectCast(argument, BoundQueryLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.LateAddressOfOperator
Dim addressOfExpression = DirectCast(argument, BoundLateAddressOfOperator)
If targetType.TypeKind <> TypeKind.Delegate AndAlso targetType.TypeKind <> TypeKind.Error Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
ReportDiagnostic(diagnostics, addressOfExpression.Syntax, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
argument = addressOfExpression.Update(addressOfExpression.Binder, addressOfExpression.MemberAccess, targetType)
Return True
Case BoundKind.AddressOfOperator
Dim delegateResolutionResult As DelegateResolutionResult = Nothing
Dim addressOfExpression = DirectCast(argument, BoundAddressOfOperator)
If addressOfExpression.GetDelegateResolutionResult(targetType, delegateResolutionResult) Then
diagnostics.AddRange(delegateResolutionResult.Diagnostics)
Dim hasErrors = True
If Conversions.ConversionExists(delegateResolutionResult.DelegateConversions) Then
Dim reclassifyBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
reclassifyBinder = New OptionStrictOffBinder(Me)
Else
reclassifyBinder = Me
End If
Debug.Assert(Not isExplicit OrElse reclassifyBinder.OptionStrict = VisualBasic.OptionStrict.Off)
argument = reclassifyBinder.ReclassifyAddressOf(addressOfExpression, delegateResolutionResult, targetType, diagnostics, isForHandles:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression)
hasErrors = argument.HasErrors
Debug.Assert(convKind = delegateResolutionResult.DelegateConversions)
End If
If argument.Kind <> BoundKind.DelegateCreationExpression Then
If conversionSemantics = SyntaxKind.CTypeKeyword Then
argument = New BoundConversion(tree, argument, convKind, False, isExplicit, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
argument = New BoundDirectCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
argument = New BoundTryCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Return True
End If
Case BoundKind.ArrayLiteral
argument = ReclassifyArrayLiteralExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundArrayLiteral), targetType, diagnostics)
Return True
Case BoundKind.InterpolatedStringExpression
argument = ReclassifyInterpolatedStringExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundInterpolatedStringExpression), targetType, diagnostics)
Return argument.Kind = BoundKind.Conversion
Case BoundKind.TupleLiteral
Dim literal = DirectCast(argument, BoundTupleLiteral)
argument = ReclassifyTupleLiteral(convKind, tree, isExplicit, literal, targetType, diagnostics)
Return argument IsNot literal
End Select
Return False
End Function
Private Function ReclassifyUnboundLambdaExpression(
unboundLambda As UnboundLambda,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetDelegateType As NamedTypeSymbol ' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim delegateInvoke As MethodSymbol
If targetType.IsStrictSupertypeOfConcreteDelegate() Then ' covers Object, System.Delegate, System.MulticastDelegate
' Reclassify the lambda as an instance of an Anonymous Delegate.
Dim anonymousDelegate As BoundExpression = ReclassifyUnboundLambdaExpression(unboundLambda, diagnostics)
#If DEBUG Then
Dim anonymousDelegateInfo As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferredAnonymousDelegate
Debug.Assert(anonymousDelegate.Type Is anonymousDelegateInfo.Key)
' If we have errors for the inference, we know that there is no conversion.
If Not anonymousDelegateInfo.Value.Diagnostics.IsDefault AndAlso anonymousDelegateInfo.Value.Diagnostics.HasAnyErrors() Then
Debug.Assert(Conversions.NoConversion(convKind) AndAlso (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
Else
Debug.Assert(Conversions.NoConversion(convKind) OrElse
(convKind And ConversionKind.DelegateRelaxationLevelMask) >= ConversionKind.DelegateRelaxationLevelWideningToNonLambda)
End If
#End If
' Now convert it to the target type.
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return ApplyConversion(tree, targetType, anonymousDelegate, isExplicit, diagnostics)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return ApplyDirectCastConversion(tree, anonymousDelegate, targetType, diagnostics)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return ApplyTryCastConversion(tree, anonymousDelegate, targetType, diagnostics)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Else
targetDelegateType = targetType.DelegateOrExpressionDelegate(Me)
If targetDelegateType Is Nothing Then
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
delegateInvoke = Nothing ' No conversion
Else
delegateInvoke = targetDelegateType.DelegateInvokeMethod
If delegateInvoke Is Nothing Then
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
delegateInvoke = Nothing ' No conversion
ElseIf ReportDelegateInvokeUseSite(diagnostics, unboundLambda.Syntax, targetDelegateType, delegateInvoke) Then
delegateInvoke = Nothing ' No conversion
ElseIf unboundLambda.IsInferredDelegateForThisLambda(delegateInvoke.ContainingType) Then
Dim inferenceDiagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol) = unboundLambda.InferredAnonymousDelegate.Value
diagnostics.AddRange(inferenceDiagnostics)
If Not inferenceDiagnostics.Diagnostics.IsDefaultOrEmpty AndAlso inferenceDiagnostics.Diagnostics.HasAnyErrors() Then
delegateInvoke = Nothing ' No conversion
End If
End If
Debug.Assert(delegateInvoke IsNot Nothing OrElse (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
End If
End If
Dim boundLambda As BoundLambda = Nothing
If delegateInvoke IsNot Nothing Then
boundLambda = unboundLambda.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(boundLambda IsNot Nothing)
If boundLambda Is Nothing Then
' An unlikely case.
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
If(unboundLambda.IsFunctionLambda, ERRID.ERR_LambdaBindingMismatch1, ERRID.ERR_LambdaBindingMismatch2),
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
End If
If boundLambda Is Nothing Then
Debug.Assert(Conversions.NoConversion(convKind))
Dim errorRecovery As BoundLambda = unboundLambda.BindForErrorRecovery()
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, errorRecovery, convKind, False, isExplicit, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Dim boundLambdaDiagnostics = boundLambda.Diagnostics
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) >= boundLambda.DelegateRelaxation)
Debug.Assert(Conversions.ClassifyMethodConversionForLambdaOrAnonymousDelegate(delegateInvoke, boundLambda.LambdaSymbol, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) = MethodConversionKind.Identity OrElse
((convKind And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelNone AndAlso
boundLambda.MethodConversionKind <> MethodConversionKind.Identity))
Dim reportedAnError As Boolean = boundLambdaDiagnostics.Diagnostics.HasAnyErrors()
diagnostics.AddRange(boundLambdaDiagnostics)
Dim relaxationLambdaOpt As BoundLambda = Nothing
If (convKind And ConversionKind.DelegateRelaxationLevelMask) = ConversionKind.DelegateRelaxationLevelInvalid AndAlso
Not reportedAnError AndAlso Not boundLambda.HasErrors Then
' We don't try to infer return type of a lambda that has both Async and Iterator modifiers, let's suppress the
' signature mismatch error in this case.
If unboundLambda.ReturnType IsNot Nothing OrElse unboundLambda.Flags <> (SourceMemberFlags.Async Or SourceMemberFlags.Iterator) Then
Dim err As ERRID
If unboundLambda.IsFunctionLambda Then
err = ERRID.ERR_LambdaBindingMismatch1
Else
err = ERRID.ERR_LambdaBindingMismatch2
End If
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
err,
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
ElseIf Conversions.IsStubRequiredForMethodConversion(boundLambda.MethodConversionKind) Then
Debug.Assert(Conversions.IsDelegateRelaxationSupportedFor(boundLambda.MethodConversionKind))
' Need to produce a stub.
' First, we need to get an Anonymous Delegate of the same shape as the lambdaSymbol.
Dim lambdaSymbol As LambdaSymbol = boundLambda.LambdaSymbol
Dim anonymousDelegateType As NamedTypeSymbol = ConstructAnonymousDelegateSymbol(unboundLambda,
(lambdaSymbol.Parameters.As(Of BoundLambdaParameterSymbol)),
lambdaSymbol.ReturnType,
diagnostics)
' Second, reclassify the bound lambda as an instance of the Anonymous Delegate.
Dim anonymousDelegateInstance = New BoundConversion(tree, boundLambda, ConversionKind.Widening Or ConversionKind.Lambda,
False, False, anonymousDelegateType)
anonymousDelegateInstance.SetWasCompilerGenerated()
' Third, create a method group representing Invoke method of the instance of the Anonymous Delegate.
Dim methodGroup = New BoundMethodGroup(unboundLambda.Syntax,
Nothing,
ImmutableArray.Create(anonymousDelegateType.DelegateInvokeMethod),
LookupResultKind.Good,
anonymousDelegateInstance,
QualificationKind.QualifiedViaValue)
methodGroup.SetWasCompilerGenerated()
' Fourth, create a lambda with the shape of the target delegate that calls the Invoke with appropriate conversions
' and drops parameters and/or return value, if needed, thus performing the relaxation.
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
relaxationLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(unboundLambda.Syntax,
delegateInvoke,
methodGroup,
boundLambda.DelegateRelaxation,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression,
diagnostics:=diagnostics)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, boundLambda, convKind, False, isExplicit, Nothing,
If(relaxationLambdaOpt Is Nothing,
Nothing,
New BoundRelaxationLambda(tree, relaxationLambdaOpt, receiverPlaceholderOpt:=Nothing).MakeCompilerGenerated()),
targetType)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End Function
Private Function ReclassifyQueryLambdaExpression(
lambda As BoundQueryLambda,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(lambda.Type Is Nothing)
' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim targetDelegateType As NamedTypeSymbol = targetType.DelegateOrExpressionDelegate(Me)
If Conversions.NoConversion(convKind) Then
If targetType.IsStrictSupertypeOfConcreteDelegate() AndAlso Not targetType.IsObjectType() Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotCreatableDelegate1, targetType)
Else
If targetDelegateType Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
Else
Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
If invoke Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
ElseIf Not ReportDelegateInvokeUseSite(diagnostics, lambda.Syntax, targetDelegateType, invoke) Then
' Conversion could fail because we couldn't convert body of the lambda
' to the target delegate type. We want to report that error instead of
' lambda signature mismatch.
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate AndAlso
Not invoke.IsSub AndAlso
Conversions.FailedDueToQueryLambdaBodyMismatch(convKind) Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax,
invoke.ReturnType,
lambda.Expression,
diagnostics,
If(invoke.ReturnType.IsBooleanType,
lambda.ExprIsOperandOfConditionalBranch,
False)),
exprIsOperandOfConditionalBranch:=False)
Else
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaBindingMismatch1, targetDelegateType)
End If
End If
End If
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Dim delegateInvoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
For Each delegateParam As ParameterSymbol In delegateInvoke.Parameters
If delegateParam.IsByRef OrElse delegateParam.OriginalDefinition.Type.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateParam.Type.IsRestrictedTypeOrArrayType(restrictedType) Then
ReportDiagnostic(diagnostics, lambda.LambdaSymbol.Parameters(delegateParam.Ordinal).Locations(0),
ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
Next
Dim delegateReturnType As TypeSymbol = delegateInvoke.ReturnType
If delegateInvoke.OriginalDefinition.ReturnType.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateReturnType.IsRestrictedTypeOrArrayType(restrictedType) Then
Dim location As SyntaxNode
If lambda.Expression.Kind = BoundKind.RangeVariableAssignment Then
location = DirectCast(lambda.Expression, BoundRangeVariableAssignment).Value.Syntax
Else
location = lambda.Expression.Syntax
End If
ReportDiagnostic(diagnostics, location, ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax, delegateReturnType, lambda.Expression,
diagnostics,
If(delegateReturnType.IsBooleanType(), lambda.ExprIsOperandOfConditionalBranch, False)),
exprIsOperandOfConditionalBranch:=False)
Else
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
lambda.Expression, exprIsOperandOfConditionalBranch:=False)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End Function
Private Function ReclassifyInterpolatedStringExpression(conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, node As BoundInterpolatedStringExpression, targetType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression
If (convKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString Then
Debug.Assert(targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_IFormattable)) OrElse targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_FormattableString)))
Return New BoundConversion(tree, node, ConversionKind.InterpolatedString, False, isExplicit, targetType)
End If
Return node
End Function
Private Function ReclassifyTupleLiteral(
convKind As ConversionKind,
tree As SyntaxNode,
isExplicit As Boolean,
sourceTuple As BoundTupleLiteral,
destination As TypeSymbol,
diagnostics As BindingDiagnosticBag) As BoundExpression
' We have a successful tuple conversion rather than producing a separate conversion node
' which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments.
Dim isNullableTupleConversion = (convKind And ConversionKind.Nullable) <> 0
Debug.Assert(Not isNullableTupleConversion OrElse destination.IsNullableType())
Dim targetType = destination
If isNullableTupleConversion Then
targetType = destination.GetNullableUnderlyingType()
End If
Dim arguments = sourceTuple.Arguments
If Not targetType.IsTupleOrCompatibleWithTupleOfCardinality(arguments.Length) Then
Return sourceTuple
End If
If targetType.IsTupleType Then
Dim destTupleType = DirectCast(targetType, TupleTypeSymbol)
TupleTypeSymbol.ReportNamesMismatchesIfAny(targetType, sourceTuple, diagnostics)
' do not lose the original element names in the literal if different from names in the target
' Come back to this, what about locations? (https:'github.com/dotnet/roslyn/issues/11013)
targetType = destTupleType.WithElementNames(sourceTuple.ArgumentNamesOpt)
End If
Dim convertedArguments = ArrayBuilder(Of BoundExpression).GetInstance(arguments.Length)
Dim targetElementTypes As ImmutableArray(Of TypeSymbol) = targetType.GetElementTypesOfTupleOrCompatible()
Debug.Assert(targetElementTypes.Length = arguments.Length, "converting a tuple literal to incompatible type?")
For i As Integer = 0 To arguments.Length - 1
Dim argument = arguments(i)
Dim destType = targetElementTypes(i)
convertedArguments.Add(ApplyConversion(argument.Syntax, destType, argument, isExplicit, diagnostics))
Next
Dim result As BoundExpression = New BoundConvertedTupleLiteral(
sourceTuple.Syntax,
sourceTuple.Type,
convertedArguments.ToImmutableAndFree(),
targetType)
If Not TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything) AndAlso convKind <> Nothing Then
' literal cast is applied to the literal
result = New BoundConversion(sourceTuple.Syntax, result, convKind, checked:=False, explicitCastInCode:=isExplicit, type:=destination)
End If
' If we had a cast in the code, keep conversion in the tree.
' even though the literal is already converted to the target type.
If isExplicit Then
result = New BoundConversion(
tree,
result,
ConversionKind.Identity,
checked:=False,
explicitCastInCode:=isExplicit,
type:=destination)
End If
Return result
End Function
Private Sub WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
)
If Conversions.IsNarrowingConversion(convKind) Then
Dim interfaceType As TypeSymbol = Nothing
Dim classType As NamedTypeSymbol = Nothing
If sourceType.IsInterfaceType() Then
If targetType.IsClassType() Then
interfaceType = sourceType
classType = DirectCast(targetType, NamedTypeSymbol)
End If
ElseIf sourceType.IsClassType() AndAlso targetType.IsInterfaceType() Then
interfaceType = targetType
classType = DirectCast(sourceType, NamedTypeSymbol)
End If
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If classType IsNot Nothing AndAlso
interfaceType IsNot Nothing AndAlso
classType.IsNotInheritable AndAlso
Not classType.IsComImport() AndAlso
Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(classType, interfaceType, useSiteInfo)) Then
' Report specific warning if converting IEnumerable(Of XElement) to String.
If (targetType.SpecialType = SpecialType.System_String) AndAlso IsIEnumerableOfXElement(sourceType, useSiteInfo) Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_UseValueForXmlExpression3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.WRN_InterfaceConversion2, sourceType, targetType)
End If
End If
diagnostics.AddDependencies(useSiteInfo)
End If
End Sub
Private Function IsIEnumerableOfXElement(type As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean
Return type.IsOrImplementsIEnumerableOfXElement(Compilation, useSiteInfo)
End Function
Private Sub ReportNoConversionError(
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
Optional copybackConversionParamName As String = Nothing
)
If sourceType.IsArrayType() AndAlso targetType.IsArrayType() Then
Dim sourceArray = DirectCast(sourceType, ArrayTypeSymbol)
Dim targetArray = DirectCast(targetType, ArrayTypeSymbol)
Dim sourceElement = sourceArray.ElementType
Dim targetElement = targetArray.ElementType
If sourceArray.Rank <> targetArray.Rank Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayRankMismatch2, sourceType, targetType)
ElseIf sourceArray.IsSZArray <> targetArray.IsSZArray Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
ElseIf Not (sourceElement.IsErrorType() OrElse targetElement.IsErrorType()) Then
Dim elemConv = Conversions.ClassifyDirectCastConversion(sourceElement, targetElement, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
If Not Conversions.IsIdentityConversion(elemConv) AndAlso
(targetElement.IsObjectType() OrElse targetElement.SpecialType = SpecialType.System_ValueType) AndAlso
Not sourceElement.IsReferenceType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertObjectArrayMismatch3, sourceType, targetType, sourceElement)
ElseIf Not Conversions.IsIdentityConversion(elemConv) AndAlso
Not (Conversions.IsWideningConversion(elemConv) AndAlso
(elemConv And (ConversionKind.Reference Or ConversionKind.Value Or ConversionKind.TypeParameter)) <> 0) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayMismatch4, sourceType, targetType, sourceElement, targetElement)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End If
ElseIf sourceType.IsDateTimeType() AndAlso targetType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DateToDoubleConversion)
ElseIf targetType.IsDateTimeType() AndAlso sourceType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DoubleToDateConversion)
ElseIf targetType.IsCharType() AndAlso sourceType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_IntegralToCharTypeMismatch1, sourceType)
ElseIf sourceType.IsCharType() AndAlso targetType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CharToIntegralTypeMismatch1, targetType)
ElseIf copybackConversionParamName IsNot Nothing Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CopyBackTypeMismatch3,
copybackConversionParamName, sourceType, targetType)
ElseIf sourceType.IsInterfaceType() AndAlso targetType.IsValueType() AndAlso IsIEnumerableOfXElement(sourceType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatchForXml3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' Binding of conversion operators is implemented in this part.
Partial Friend Class Binder
Private Function BindCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim result As BoundExpression
Select Case node.Keyword.Kind
Case SyntaxKind.CTypeKeyword
result = BindCTypeExpression(node, diagnostics)
Case SyntaxKind.DirectCastKeyword
result = BindDirectCastExpression(node, diagnostics)
Case SyntaxKind.TryCastKeyword
result = BindTryCastExpression(node, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return result
End Function
Private Function BindCTypeExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.CTypeKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyConversion(node, targetType, argument, isExplicit:=True, diagnostics)
End Function
Private Function BindDirectCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.DirectCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyDirectCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyDirectCastConversion(
node As SyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundDirectCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True)
End If
' Classify conversion
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If ReclassifyExpression(argument, SyntaxKind.DirectCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.DirectCast, "Associated wrong node with conversion?")
argument = New BoundDirectCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundDirectCast(node, argument, conv, targetType, hasErrors:=True)
End If
If Conversions.IsIdentityConversion(conv) Then
If targetType.IsFloatingType() Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_IdentityDirectCastForFloat)
ElseIf targetType.IsValueType Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ObsoleteIdentityDirectCastForValueType)
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
Debug.Assert(Conversions.IsIdentityConversion(conv) OrElse
conv = ConversionKind.WideningNothingLiteral OrElse
sourceType.GetEnumUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(targetType.GetEnumUnderlyingTypeOrSelf()))
Debug.Assert(Not integerOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
End If
Return New BoundDirectCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindTryCastExpression(
node As CastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.TryCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyTryCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyTryCastConversion(
node As SyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundTryCast(node, argument, conversionKind:=Nothing, type:=targetType, hasErrors:=True)
End If
' Classify conversion
Dim conv As ConversionKind
If targetType.IsReferenceType Then
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
conv = Conversions.ClassifyTryCastConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
Else
conv = Nothing
End If
If ReclassifyExpression(argument, SyntaxKind.TryCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.TryCast, "Associated wrong node with conversion?")
argument = New BoundTryCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If targetType.IsValueType() Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfValueType1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
ElseIf targetType.IsTypeParameter() AndAlso Not targetType.IsReferenceType Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfUnconstrainedTypeParam1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
ElseIf sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundTryCast(node, argument, conv, targetType, hasErrors:=True)
End If
Dim constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
Return New BoundTryCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindPredefinedCastExpression(
node As PredefinedCastExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetType As SpecialType
Select Case node.Keyword.Kind
Case SyntaxKind.CBoolKeyword : targetType = SpecialType.System_Boolean
Case SyntaxKind.CByteKeyword : targetType = SpecialType.System_Byte
Case SyntaxKind.CCharKeyword : targetType = SpecialType.System_Char
Case SyntaxKind.CDateKeyword : targetType = SpecialType.System_DateTime
Case SyntaxKind.CDecKeyword : targetType = SpecialType.System_Decimal
Case SyntaxKind.CDblKeyword : targetType = SpecialType.System_Double
Case SyntaxKind.CIntKeyword : targetType = SpecialType.System_Int32
Case SyntaxKind.CLngKeyword : targetType = SpecialType.System_Int64
Case SyntaxKind.CObjKeyword : targetType = SpecialType.System_Object
Case SyntaxKind.CSByteKeyword : targetType = SpecialType.System_SByte
Case SyntaxKind.CShortKeyword : targetType = SpecialType.System_Int16
Case SyntaxKind.CSngKeyword : targetType = SpecialType.System_Single
Case SyntaxKind.CStrKeyword : targetType = SpecialType.System_String
Case SyntaxKind.CUIntKeyword : targetType = SpecialType.System_UInt32
Case SyntaxKind.CULngKeyword : targetType = SpecialType.System_UInt64
Case SyntaxKind.CUShortKeyword : targetType = SpecialType.System_UInt16
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return ApplyConversion(node, GetSpecialType(targetType, node.Keyword, diagnostics),
BindValue(node.Expression, diagnostics),
isExplicit:=True, diagnostics:=diagnostics)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Friend Function ApplyImplicitConversion(
node As SyntaxNode,
targetType As TypeSymbol,
expression As BoundExpression,
diagnostics As BindingDiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False
) As BoundExpression
Return ApplyConversion(node, targetType, expression, False, diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of explicit or non-identity conversion.
''' </summary>
Private Function ApplyConversion(
node As SyntaxNode,
targetType As TypeSymbol,
argument As BoundExpression,
isExplicit As Boolean,
diagnostics As BindingDiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(node IsNot Nothing)
Debug.Assert(Not isOperandOfConditionalBranch OrElse Not isExplicit)
Debug.Assert(argument.IsValue())
' Deal with erroneous arguments
If targetType.IsErrorType Then
argument = MakeRValueAndIgnoreDiagnostics(argument)
If Not isExplicit AndAlso argument.Type.IsSameTypeIgnoringAll(targetType) Then
Return argument
End If
Return New BoundConversion(node,
argument,
conversionKind:=Nothing,
checked:=CheckOverflow,
explicitCastInCode:=isExplicit,
type:=targetType,
hasErrors:=True)
End If
If argument.HasErrors Then
' Suppress any additional diagnostics produced by this function
diagnostics = BindingDiagnosticBag.Discarded
End If
' Classify conversion
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol)
Dim applyNullableIsTrueOperator As Boolean = False
Dim isTrueOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim result As BoundExpression
Debug.Assert(Not isOperandOfConditionalBranch OrElse targetType.IsBooleanType())
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If isOperandOfConditionalBranch AndAlso targetType.IsBooleanType() Then
Debug.Assert(Not isExplicit)
conv = Conversions.ClassifyConversionOfOperandOfConditionalBranch(argument, targetType, Me,
applyNullableIsTrueOperator,
isTrueOperator,
useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If isTrueOperator.BestResult.HasValue Then
' Apply IsTrue operator.
Dim isTrue As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, UnaryOperatorKind.IsTrue, argument, isTrueOperator, diagnostics)
isTrue.SetWasCompilerGenerated()
isTrue.UnderlyingExpression.SetWasCompilerGenerated()
result = isTrue
Else
Dim intermediateTargetType As TypeSymbol
If applyNullableIsTrueOperator Then
' Note, use site error will be reported by ApplyNullableIsTrueOperator later.
Dim nullableOfT As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Nullable_T)
intermediateTargetType = Compilation.GetSpecialType(SpecialType.System_Nullable_T).
Construct(ImmutableArray.Create(Of TypeSymbol)(targetType))
Else
intermediateTargetType = targetType
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, intermediateTargetType, diagnostics)
End If
If applyNullableIsTrueOperator Then
result = Binder.ApplyNullableIsTrueOperator(result, targetType)
End If
Else
conv = Conversions.ClassifyConversion(argument, targetType, Me, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress any additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, targetType, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
End If
Return result
End Function
Private Shared Function ApplyNullableIsTrueOperator(argument As BoundExpression, booleanType As TypeSymbol) As BoundNullableIsTrueOperator
Debug.Assert(argument.Type.IsNullableOfBoolean() AndAlso booleanType.IsBooleanType())
Return New BoundNullableIsTrueOperator(argument.Syntax, argument, booleanType).MakeCompilerGenerated()
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Private Function CreateConversionAndReportDiagnostic(
tree As SyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
Optional copybackConversionParamName As String = Nothing,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(argument.IsValue())
' We need to preserve any conversion that was explicitly written in code
' (so that GetSemanticInfo can find the syntax in the bound tree). Implicit identity conversion
' don't need representation in the bound tree (they would be optimized away in emit, but are so common
' that this is an important way to save both time and memory).
If (Not isExplicit OrElse explicitSemanticForConcatArgument) AndAlso Conversions.IsIdentityConversion(convKind.Key) Then
Debug.Assert(argument.Type.IsSameTypeIgnoringAll(targetType))
Debug.Assert(tree Is argument.Syntax)
Return MakeRValue(argument, diagnostics)
End If
If (convKind.Key And ConversionKind.UserDefined) = 0 AndAlso
ReclassifyExpression(argument, SyntaxKind.CTypeKeyword, tree, convKind.Key, isExplicit, targetType, diagnostics) Then
argument = MakeRValue(argument, diagnostics)
If isExplicit AndAlso argument.Syntax IsNot tree Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
argument = New BoundConversion(tree, argument, ConversionKind.Identity, CheckOverflow, isExplicit, targetType)
End If
Return argument
ElseIf Not argument.IsNothingLiteral() AndAlso argument.Kind <> BoundKind.ArrayLiteral Then
argument = MakeRValue(argument, diagnostics)
End If
Debug.Assert(argument.Kind <> BoundKind.Conversion OrElse DirectCast(argument, BoundConversion).ExplicitCastInCode OrElse
Not argument.IsNothingLiteral() OrElse
TypeOf argument.Syntax.Parent Is BinaryExpressionSyntax OrElse
TypeOf argument.Syntax.Parent Is UnaryExpressionSyntax OrElse
TypeOf argument.Syntax.Parent Is TupleExpressionSyntax OrElse
(TypeOf argument.Syntax.Parent Is AssignmentStatementSyntax AndAlso argument.Syntax.Parent.Kind <> SyntaxKind.SimpleAssignmentStatement),
"Applying yet another conversion to an implicit conversion from NOTHING, probably MakeRValue was called too early.")
Dim sourceType = argument.Type
' At this point if the expression is an array literal then the conversion must be user defined.
Debug.Assert(argument.Kind <> BoundKind.ArrayLiteral OrElse (convKind.Key And ConversionKind.UserDefined) <> 0)
Dim reportArrayLiteralElementNarrowingConversion = False
If argument.Kind = BoundKind.ArrayLiteral Then
' The array will get the type from the input type of the user defined conversion.
sourceType = convKind.Value.Parameters(0).Type
' If the conversion from the inferred element type to the source type of the user defined conversion is a narrowing conversion then
' skip to the user defined conversion. Conversion errors on the individual elements will be reported when the array literal is reclassified.
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
reportArrayLiteralElementNarrowingConversion =
Not isExplicit AndAlso
Conversions.IsNarrowingConversion(convKind.Key) AndAlso
Conversions.IsNarrowingConversion(Conversions.ClassifyArrayLiteralConversion(DirectCast(argument, BoundArrayLiteral), sourceType, Me, useSiteInfo))
diagnostics.Add(argument.Syntax, useSiteInfo)
If reportArrayLiteralElementNarrowingConversion Then
GoTo DoneWithDiagnostics
End If
End If
If argument.HasErrors Then
GoTo DoneWithDiagnostics
End If
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
GoTo DoneWithDiagnostics
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(convKind.Key) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics)
' Deal with implicit narrowing conversions
If Not isExplicit AndAlso Conversions.IsNarrowingConversion(convKind.Key) AndAlso
(convKind.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If copybackConversionParamName IsNot Nothing Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_StrictArgumentCopyBackNarrowing3,
copybackConversionParamName, sourceType, targetType)
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ImplicitConversionCopyBack,
copybackConversionParamName, sourceType, targetType)
End If
Else
' We have a narrowing conversion. This is how we might display it, depending on context:
' ERR_NarrowingConversionDisallowed2 "Option Strict On disallows implicit conversions from '|1' to '|2'."
' ERR_NarrowingConversionCollection2 "Option Strict On disallows implicit conversions from '|1' to '|2';
' the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type."
' ERR_AmbiguousCastConversion2 "Option Strict On disallows implicit conversions from '|1' to '|2' because the conversion is ambiguous."
' The Collection error is for when one type is Microsoft.VisualBasic.Collection and
' the other type is named _Collection.
' The Ambiguous error is for when the conversion was classed as "Narrowing" for reasons of ambiguity.
If OptionStrict = VisualBasic.OptionStrict.On Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
Dim err As ERRID = ERRID.ERR_NarrowingConversionDisallowed2
Const _Collection As String = "_Collection"
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
err = ERRID.ERR_AmbiguousCastConversion2
ElseIf (sourceType.IsMicrosoftVisualBasicCollection() AndAlso String.Equals(targetType.Name, _Collection, StringComparison.Ordinal)) OrElse
(String.Equals(sourceType.Name, _Collection, StringComparison.Ordinal) AndAlso targetType.IsMicrosoftVisualBasicCollection()) Then
' Got both, so use the more specific error message
err = ERRID.ERR_NarrowingConversionCollection2
End If
ReportDiagnostic(diagnostics, argument.Syntax, err, sourceType, targetType)
End If
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
' Avoid reporting a warning if narrowing caused exclusively by "zero argument" relaxation
' for an Anonymous Delegate. Note, that dropping a return is widening.
If (convKind.Key And ConversionKind.AnonymousDelegate) = 0 OrElse
(convKind.Key And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=True) Then
Dim wrnId1 As ERRID = ERRID.WRN_ImplicitConversionSubst1
Dim wrnId2 As ERRID = ERRID.WRN_ImplicitConversion2
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
wrnId2 = ERRID.WRN_AmbiguousCastConversion2
End If
ReportDiagnostic(diagnostics, argument.Syntax, wrnId1, ErrorFactory.ErrorInfo(wrnId2, sourceType, targetType))
End If
End If
End If
End If
End If
If Conversions.NoConversion(convKind.Key) Then
If Conversions.FailedDueToNumericOverflow(convKind.Key) Then
Dim errorTargetType As TypeSymbol
If (convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing Then
errorTargetType = convKind.Value.Parameters(0).Type
Else
errorTargetType = targetType
End If
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ExpressionOverflow1, errorTargetType)
ElseIf isExplicit OrElse Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics, copybackConversionParamName)
End If
Return New BoundConversion(tree, argument, convKind.Key And (Not ConversionKind.UserDefined), CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
DoneWithDiagnostics:
If (convKind.Key And ConversionKind.UserDefined) <> 0 Then
Return CreateUserDefinedConversion(tree, argument, convKind, isExplicit, targetType, reportArrayLiteralElementNarrowingConversion, diagnostics)
End If
If argument.HasErrors OrElse (sourceType IsNot Nothing AndAlso sourceType.IsErrorType()) Then
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, hasErrors:=True)
End If
Return CreatePredefinedConversion(tree, argument, convKind.Key, isExplicit, targetType, diagnostics)
End Function
Private Structure VarianceSuggestionTypeParameterInfo
Private _isViable As Boolean
Private _typeParameter As TypeParameterSymbol
Private _derivedArgument As TypeSymbol
Private _baseArgument As TypeSymbol
Public Sub [Set](parameter As TypeParameterSymbol, derived As TypeSymbol, base As TypeSymbol)
_typeParameter = parameter
_derivedArgument = derived
_baseArgument = base
_isViable = True
End Sub
Public ReadOnly Property IsViable As Boolean
Get
Return _isViable
End Get
End Property
Public ReadOnly Property TypeParameter As TypeParameterSymbol
Get
Return _typeParameter
End Get
End Property
Public ReadOnly Property DerivedArgument As TypeSymbol
Get
Return _derivedArgument
End Get
End Property
Public ReadOnly Property BaseArgument As TypeSymbol
Get
Return _baseArgument
End Get
End Property
End Structure
''' <summary>
''' Returns True if error or warning was reported.
'''
''' This function is invoked on the occasion of a Narrowing or NoConversion.
''' It looks at the conversion. If the conversion could have been helped by variance in
''' some way, it reports an error/warning message to that effect and returns true. This
''' message is a substitute for whatever other conversion-failed message might have been displayed.
'''
''' Note: these variance-related messages will NOT show auto-correct suggestion of using CType. That's
''' because, in these cases, it's more likely than not that CType will fail, so it would be a bad suggestion
''' </summary>
Private Function MakeVarianceConversionSuggestion(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
justWarn As Boolean
) As Boolean
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim result As Boolean = MakeVarianceConversionSuggestion(convKind, location, sourceType, targetType, diagnostics, useSiteInfo, justWarn)
diagnostics.AddDependencies(useSiteInfo)
Return result
End Function
Private Function MakeVarianceConversionSuggestion(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
justWarn As Boolean
) As Boolean
If (convKind And ConversionKind.UserDefined) <> 0 Then
Return False
End If
' Variance scenario 2: Dim x As List(Of Animal) = New List(Of Tiger)
' "List(Of Tiger) cannot be converted to List(Of Animal). Consider using IEnumerable(Of Animal) instead."
'
' (1) If the user attempts a conversion to DEST which is a generic binding of one of the non-variant
' standard generic collection types List(Of D), Collection(Of D), ReadOnlyCollection(Of D),
' IList(Of D), ICollection(Of D)
' (2) and if the conversion failed (either ConversionNarrowing or ConversionError),
' (3) and if the source type SOURCE implemented/inherited exactly one binding ISOURCE=G(Of S) of that
' generic collection type G
' (4) and if there is a reference conversion from S to D
' (5) Then report "G(Of S) cannot be converted to G(Of D). Consider converting to IEnumerable(Of D) instead."
If targetType.Kind <> SymbolKind.NamedType Then
Return False
End If
Dim targetNamedType = DirectCast(targetType, NamedTypeSymbol)
If Not targetNamedType.IsGenericType Then
Return False
End If
Dim targetGenericDefinition As NamedTypeSymbol = targetNamedType.OriginalDefinition
If targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_List_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_Collection_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T) Then
Dim sourceTypeArgument As TypeSymbol = Nothing
If targetGenericDefinition.IsInterfaceType() Then
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteInfo:=useSiteInfo, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
sourceTypeArgument = matchingInterfaces(0).TypeArgumentsNoUseSiteDiagnostics(0)
End If
Else
Dim typeToCheck As TypeSymbol = sourceType
Do
If typeToCheck.OriginalDefinition Is targetGenericDefinition Then
sourceTypeArgument = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
Exit Do
End If
typeToCheck = typeToCheck.BaseTypeNoUseSiteDiagnostics
Loop While typeToCheck IsNot Nothing
End If
If sourceTypeArgument IsNot Nothing AndAlso
Conversions.IsWideningConversion(Conversions.Classify_Reference_Array_TypeParameterConversion(sourceTypeArgument,
targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0),
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)) Then
Dim iEnumerable_T As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
If Not iEnumerable_T.IsErrorType() Then
Dim suggestion As NamedTypeSymbol = iEnumerable_T.Construct(targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0))
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(ERRID.WRN_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion))
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion)
End If
Return True
End If
End If
End If
' Variance scenario 1: | Variance scenario 3:
' Dim x as IEnumerable(Of Tiger) = New List(Of Animal) | Dim x As IGoo(Of Animal) = New MyGoo
' "List(Of Animal) cannot be converted to | "MyGoo cannot be converted to IGoo(Of Animal).
' IEnumerable(Of Tiger) because 'Animal' is not derived | Consider changing the 'T' in the definition
' from 'Tiger', as required for the 'Out' generic | of interface IGoo(Of T) to an Out type
' parameter 'T' in 'IEnumerable(Of Out T)'" | parameter, Out T."
' |
' (1) If the user attempts a conversion to | (1) If the user attempts a conversion to some
' some target type DEST=G(Of D1,D2,...) which is | target type DEST=G(Of D1,D2,...) which is
' a generic instantiation of some variant interface/| a generic instantiation of some interface/delegate
' delegate type G(Of T1,T2,...), | type G(...), which NEED NOT be variant!
' (2) and if the conversion fails (Narrowing/Error), | (2) and if the type G is defined in source-code,
' (3) and if the source type SOURCE implements/ | not imported metadata. And the conversion fails.
' inherits exactly one binding INHSOURCE= | (3) And INHSOURCE=exactly one binding of G
' G(Of S1,S2,...) of that generic type G, | (4) And if ever difference is either Di/Si/Ti
' (4) and if the only differences between (D1,D2,...) | where Ti has In/Out variance, or is
' and (S1,S2,...) occur in positions "Di/Si" | Dj/Sj/Tj such that Tj has no variance and
' such that the corresponding Ti has either In | Dj has a CLR conversion to Sj or vice versa
' or Out variance | (5) Then pick the first difference Dj/Sj
' (5) Then pick on the one such difference Si/Di/Ti | (6) and report "SOURCE cannot be converted to
' (6) and report "SOURCE cannot be converted to DEST | DEST. Consider changing Tj in the definition
' because Si is not derived from Di, as required | of interface/delegate IGoo(Of T) to an
' for the 'In/Out' generic parameter 'T' in | In/Out type parameter, In/Out T".
' 'IEnumerable(Of Out T)'" |
Dim matchingGenericInstantiation As NamedTypeSymbol
' (1) If the user attempts a conversion
Select Case targetGenericDefinition.TypeKind
Case TypeKind.Delegate
If sourceType.OriginalDefinition Is targetGenericDefinition Then
matchingGenericInstantiation = DirectCast(sourceType, NamedTypeSymbol)
Else
Return False
End If
Case TypeKind.Interface
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteInfo:=useSiteInfo, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
matchingGenericInstantiation = matchingInterfaces(0)
Else
Return False
End If
Case Else
Return False
End Select
' (3) and if the source type implemented exactly one binding of it...
Dim source As NamedTypeSymbol = matchingGenericInstantiation
Dim destination As NamedTypeSymbol = targetNamedType
Dim oneVariantDifference As VarianceSuggestionTypeParameterInfo = Nothing ' for Di/Si/Ti
Dim oneInvariantConvertibleDifference As TypeParameterSymbol = Nothing 'for Dj/Sj/Tj where Sj<Dj
Dim oneInvariantReverseConvertibleDifference As TypeParameterSymbol = Nothing ' Dj/Sj/Tj where Dj<Sj
Do
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol) = source.TypeParameters
Dim sourceArguments As ImmutableArray(Of TypeSymbol) = source.TypeArgumentsNoUseSiteDiagnostics
Dim destinationArguments As ImmutableArray(Of TypeSymbol) = destination.TypeArgumentsNoUseSiteDiagnostics
For i As Integer = 0 To typeParameters.Length - 1
Dim sourceArg As TypeSymbol = sourceArguments(i)
Dim destinationArg As TypeSymbol = destinationArguments(i)
If sourceArg.IsSameTypeIgnoringAll(destinationArg) Then
Continue For
End If
If sourceArg.IsErrorType() OrElse destinationArg.IsErrorType() Then
Continue For
End If
Dim conv As ConversionKind = Nothing
Select Case typeParameters(i).Variance
Case VarianceKind.Out
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(sourceArg, destinationArg,
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)
If Not Conversions.IsWideningConversion(conv) Then
If Not Conversions.IsNarrowingConversion(conv) OrElse (conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
End If
End If
End If
Case VarianceKind.In
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(destinationArg, sourceArg,
varianceCompatibilityClassificationDepth:=0,
useSiteInfo:=useSiteInfo)
If Not Conversions.IsWideningConversion(conv) Then
If (targetNamedType.IsDelegateType AndAlso destinationArg.IsReferenceType AndAlso sourceArg.IsReferenceType) OrElse
Not Conversions.IsNarrowingConversion(conv) OrElse
(conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
End If
End If
End If
Case Else
conv = Conversions.ClassifyDirectCastConversion(sourceArg, destinationArg, useSiteInfo)
If Conversions.IsWideningConversion(conv) Then
oneInvariantConvertibleDifference = typeParameters(i)
Else
conv = Conversions.ClassifyDirectCastConversion(destinationArg, sourceArg, useSiteInfo)
If Conversions.IsWideningConversion(conv) Then
oneInvariantReverseConvertibleDifference = typeParameters(i)
Else
Return False
End If
End If
End Select
Next
source = source.ContainingType
destination = destination.ContainingType
Loop While source IsNot Nothing
' (5) If a Di/Si/Ti, and no Dj/Sj/Tj nor Dk/Sk/Tk, then report...
If oneVariantDifference.IsViable AndAlso
oneInvariantConvertibleDifference Is Nothing AndAlso
oneInvariantReverseConvertibleDifference Is Nothing Then
Dim containerFormatter As FormattedSymbol
If oneVariantDifference.TypeParameter.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneVariantDifference.TypeParameter.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneVariantDifference.TypeParameter.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.WRN_VarianceConversionFailedOut6,
ERRID.WRN_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType))
Else
ReportDiagnostic(diagnostics, location, If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.ERR_VarianceConversionFailedOut6,
ERRID.ERR_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType)
End If
Return True
End If
' (5b) Otherwise, if a Dj/Sj/Tj and no Dk/Sk/Tk, and G came not from metadata, then report...
If (oneInvariantConvertibleDifference IsNot Nothing OrElse oneInvariantReverseConvertibleDifference IsNot Nothing) AndAlso
targetType.ContainingModule Is Compilation.SourceModule Then
Dim oneInvariantDifference As TypeParameterSymbol
If oneInvariantConvertibleDifference IsNot Nothing Then
oneInvariantDifference = oneInvariantConvertibleDifference
Else
oneInvariantDifference = oneInvariantReverseConvertibleDifference
End If
Dim containerFormatter As FormattedSymbol
If oneInvariantDifference.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneInvariantDifference.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneInvariantDifference.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.WRN_VarianceConversionFailedTryOut4,
ERRID.WRN_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter))
Else
ReportDiagnostic(diagnostics, location, If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.ERR_VarianceConversionFailedTryOut4,
ERRID.ERR_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter)
End If
Return True
End If
Return False
End Function
Private Function CreatePredefinedConversion(
tree As SyntaxNode,
argument As BoundExpression,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundConversion
Debug.Assert(Conversions.ConversionExists(convKind) AndAlso (convKind And ConversionKind.UserDefined) = 0)
Dim sourceType = argument.Type
' Handle Anonymous Delegate conversion.
If (convKind And ConversionKind.AnonymousDelegate) <> 0 Then
' Don't spend time building a narrowing relaxation stub if we already complained about the narrowing.
If isExplicit OrElse OptionStrict <> VisualBasic.OptionStrict.On OrElse Conversions.IsWideningConversion(convKind) Then
Debug.Assert(Not Conversions.IsIdentityConversion(convKind))
Debug.Assert(sourceType.IsDelegateType() AndAlso DirectCast(sourceType, NamedTypeSymbol).IsAnonymousType AndAlso targetType.IsDelegateType() AndAlso
targetType.SpecialType <> SpecialType.System_MulticastDelegate)
Dim boundLambdaOpt As BoundLambda = Nothing
Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = Nothing
Dim methodToConvert As MethodSymbol = DirectCast(sourceType, NamedTypeSymbol).DelegateInvokeMethod
If (convKind And ConversionKind.NeedAStub) <> 0 Then
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
boundLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(tree, tree, argument, methodToConvert,
Nothing, QualificationKind.QualifiedViaValue,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
convKind And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=False,
diagnostics:=diagnostics,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholderOpt)
End If
' The conversion has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later the node get's rewritten into a delegate creation with the lambda if needed.
Return New BoundConversion(tree, argument, convKind, False, isExplicit, Nothing,
If(boundLambdaOpt Is Nothing,
Nothing,
New BoundRelaxationLambda(tree, boundLambdaOpt, relaxationReceiverPlaceholderOpt).MakeCompilerGenerated()),
targetType)
Else
Debug.Assert(Not diagnostics.AccumulatesDiagnostics OrElse diagnostics.HasAnyErrors())
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
' Overflow should have been detected at classification time.
Debug.Assert(Not integerOverflow OrElse Not CheckOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, convKind, targetType)
End If
Dim tupleElements As BoundConvertedTupleElements = CreateConversionForTupleElements(tree, sourceType, targetType, convKind, isExplicit)
Return New BoundConversion(tree, argument, convKind, CheckOverflow, isExplicit, constantResult, tupleElements, targetType)
End Function
Private Function CreateConversionForTupleElements(
tree As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
convKind As ConversionKind,
isExplicit As Boolean
) As BoundConvertedTupleElements
If (convKind And ConversionKind.Tuple) <> 0 Then
Dim sourceElementTypes = sourceType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible()
Dim targetElementTypes = targetType.GetNullableUnderlyingTypeOrSelf().GetElementTypesOfTupleOrCompatible()
Dim placeholders = ArrayBuilder(Of BoundRValuePlaceholder).GetInstance(sourceElementTypes.Length)
Dim converted = ArrayBuilder(Of BoundExpression).GetInstance(sourceElementTypes.Length)
For i As Integer = 0 To sourceElementTypes.Length - 1
Dim placeholder = New BoundRValuePlaceholder(tree, sourceElementTypes(i)).MakeCompilerGenerated()
placeholders.Add(placeholder)
converted.Add(ApplyConversion(tree, targetElementTypes(i), placeholder, isExplicit, BindingDiagnosticBag.Discarded))
Next
Return New BoundConvertedTupleElements(tree, placeholders.ToImmutableAndFree(), converted.ToImmutableAndFree()).MakeCompilerGenerated()
End If
Return Nothing
End Function
Private Function CreateUserDefinedConversion(
tree As SyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
reportArrayLiteralElementNarrowingConversion As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundConversion
Debug.Assert((convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing AndAlso
convKind.Value.ParameterCount = 1 AndAlso Not convKind.Value.IsSub AndAlso
Not convKind.Value.Parameters(0).IsByRef AndAlso convKind.Value.IsShared)
' Suppress any Option Strict diagnostics.
Dim conversionBinder = New OptionStrictOffBinder(Me)
Dim argumentSyntax = argument.Syntax
Dim originalArgumentType As TypeSymbol = argument.Type
Dim inType As TypeSymbol = convKind.Value.Parameters(0).Type
Dim outType As TypeSymbol = convKind.Value.ReturnType
Dim intermediateConv As ConversionKind
Dim inOutConversionFlags As Byte = 0
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If argument.Kind = BoundKind.ArrayLiteral Then
' For array literals, report Option Strict diagnostics for each element when reportArrayLiteralElementNarrowingConversion is true.
Dim arrayLiteral = DirectCast(argument, BoundArrayLiteral)
Dim arrayLiteralBinder = If(reportArrayLiteralElementNarrowingConversion, Me, conversionBinder)
intermediateConv = Conversions.ClassifyArrayLiteralConversion(arrayLiteral, inType, arrayLiteralBinder, useSiteInfo)
argument = arrayLiteralBinder.ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, tree,
intermediateConv,
isExplicit,
arrayLiteral,
inType, diagnostics)
originalArgumentType = inType
Else
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, inType, conversionBinder, useSiteInfo)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, inType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = 1
End If
End If
ReportUseSite(diagnostics, tree, convKind.Value)
ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, convKind.Value, tree)
Debug.Assert(convKind.Value.IsUserDefinedOperator())
If Me.ContainingMember Is convKind.Value Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.WRN_RecursiveOperatorCall, convKind.Value)
End If
argument = New BoundCall(tree,
method:=convKind.Value,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray.Create(Of BoundExpression)(argument),
constantValueOpt:=Nothing,
suppressObjectClone:=True,
type:=outType).MakeCompilerGenerated()
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, targetType, conversionBinder, useSiteInfo)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, targetType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = inOutConversionFlags Or CByte(2)
End If
argument = New BoundUserDefinedConversion(tree, argument, inOutConversionFlags, originalArgumentType).MakeCompilerGenerated()
diagnostics.Add(tree, useSiteInfo)
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, DirectCast(Nothing, ConstantValue), targetType)
End Function
''' <summary>
''' Handle expression reclassification, if any applicable.
'''
''' If function returns True, the "argument" parameter has been replaced
''' with result of reclassification (possibly an error node) and appropriate
''' diagnostic, if any, has been reported.
'''
''' If function returns false, the "argument" parameter must be unchanged and no
''' diagnostic should be reported.
'''
''' conversionSemantics can be one of these:
''' SyntaxKind.CTypeKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.TryCastKeyword
''' </summary>
Private Function ReclassifyExpression(
ByRef argument As BoundExpression,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.GroupTypeInferenceLambda)
Select Case argument.Kind
Case BoundKind.Parenthesized
If argument.Type Is Nothing AndAlso Not argument.IsNothingLiteral() Then
Dim parenthesized = DirectCast(argument, BoundParenthesized)
Dim enclosed As BoundExpression = parenthesized.Expression
' Reclassify enclosed expression.
If ReclassifyExpression(enclosed, conversionSemantics, enclosed.Syntax, convKind, isExplicit, targetType, diagnostics) Then
argument = parenthesized.Update(enclosed, enclosed.Type)
Return True
End If
End If
Case BoundKind.UnboundLambda
argument = ReclassifyUnboundLambdaExpression(DirectCast(argument, UnboundLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.QueryLambda
argument = ReclassifyQueryLambdaExpression(DirectCast(argument, BoundQueryLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.LateAddressOfOperator
Dim addressOfExpression = DirectCast(argument, BoundLateAddressOfOperator)
If targetType.TypeKind <> TypeKind.Delegate AndAlso targetType.TypeKind <> TypeKind.Error Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
ReportDiagnostic(diagnostics, addressOfExpression.Syntax, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
argument = addressOfExpression.Update(addressOfExpression.Binder, addressOfExpression.MemberAccess, targetType)
Return True
Case BoundKind.AddressOfOperator
Dim delegateResolutionResult As DelegateResolutionResult = Nothing
Dim addressOfExpression = DirectCast(argument, BoundAddressOfOperator)
If addressOfExpression.GetDelegateResolutionResult(targetType, delegateResolutionResult) Then
diagnostics.AddRange(delegateResolutionResult.Diagnostics)
Dim hasErrors = True
If Conversions.ConversionExists(delegateResolutionResult.DelegateConversions) Then
Dim reclassifyBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
reclassifyBinder = New OptionStrictOffBinder(Me)
Else
reclassifyBinder = Me
End If
Debug.Assert(Not isExplicit OrElse reclassifyBinder.OptionStrict = VisualBasic.OptionStrict.Off)
argument = reclassifyBinder.ReclassifyAddressOf(addressOfExpression, delegateResolutionResult, targetType, diagnostics, isForHandles:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression)
hasErrors = argument.HasErrors
Debug.Assert(convKind = delegateResolutionResult.DelegateConversions)
End If
If argument.Kind <> BoundKind.DelegateCreationExpression Then
If conversionSemantics = SyntaxKind.CTypeKeyword Then
argument = New BoundConversion(tree, argument, convKind, False, isExplicit, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
argument = New BoundDirectCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
argument = New BoundTryCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Return True
End If
Case BoundKind.ArrayLiteral
argument = ReclassifyArrayLiteralExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundArrayLiteral), targetType, diagnostics)
Return True
Case BoundKind.InterpolatedStringExpression
argument = ReclassifyInterpolatedStringExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundInterpolatedStringExpression), targetType, diagnostics)
Return argument.Kind = BoundKind.Conversion
Case BoundKind.TupleLiteral
Dim literal = DirectCast(argument, BoundTupleLiteral)
argument = ReclassifyTupleLiteral(convKind, tree, isExplicit, literal, targetType, diagnostics)
Return argument IsNot literal
End Select
Return False
End Function
Private Function ReclassifyUnboundLambdaExpression(
unboundLambda As UnboundLambda,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetDelegateType As NamedTypeSymbol ' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim delegateInvoke As MethodSymbol
If targetType.IsStrictSupertypeOfConcreteDelegate() Then ' covers Object, System.Delegate, System.MulticastDelegate
' Reclassify the lambda as an instance of an Anonymous Delegate.
Dim anonymousDelegate As BoundExpression = ReclassifyUnboundLambdaExpression(unboundLambda, diagnostics)
#If DEBUG Then
Dim anonymousDelegateInfo As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferredAnonymousDelegate
Debug.Assert(anonymousDelegate.Type Is anonymousDelegateInfo.Key)
' If we have errors for the inference, we know that there is no conversion.
If Not anonymousDelegateInfo.Value.Diagnostics.IsDefault AndAlso anonymousDelegateInfo.Value.Diagnostics.HasAnyErrors() Then
Debug.Assert(Conversions.NoConversion(convKind) AndAlso (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
Else
Debug.Assert(Conversions.NoConversion(convKind) OrElse
(convKind And ConversionKind.DelegateRelaxationLevelMask) >= ConversionKind.DelegateRelaxationLevelWideningToNonLambda)
End If
#End If
' Now convert it to the target type.
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return ApplyConversion(tree, targetType, anonymousDelegate, isExplicit, diagnostics)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return ApplyDirectCastConversion(tree, anonymousDelegate, targetType, diagnostics)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return ApplyTryCastConversion(tree, anonymousDelegate, targetType, diagnostics)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Else
targetDelegateType = targetType.DelegateOrExpressionDelegate(Me)
If targetDelegateType Is Nothing Then
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
delegateInvoke = Nothing ' No conversion
Else
delegateInvoke = targetDelegateType.DelegateInvokeMethod
If delegateInvoke Is Nothing Then
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
delegateInvoke = Nothing ' No conversion
ElseIf ReportDelegateInvokeUseSite(diagnostics, unboundLambda.Syntax, targetDelegateType, delegateInvoke) Then
delegateInvoke = Nothing ' No conversion
ElseIf unboundLambda.IsInferredDelegateForThisLambda(delegateInvoke.ContainingType) Then
Dim inferenceDiagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol) = unboundLambda.InferredAnonymousDelegate.Value
diagnostics.AddRange(inferenceDiagnostics)
If Not inferenceDiagnostics.Diagnostics.IsDefaultOrEmpty AndAlso inferenceDiagnostics.Diagnostics.HasAnyErrors() Then
delegateInvoke = Nothing ' No conversion
End If
End If
Debug.Assert(delegateInvoke IsNot Nothing OrElse (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
End If
End If
Dim boundLambda As BoundLambda = Nothing
If delegateInvoke IsNot Nothing Then
boundLambda = unboundLambda.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(boundLambda IsNot Nothing)
If boundLambda Is Nothing Then
' An unlikely case.
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
If(unboundLambda.IsFunctionLambda, ERRID.ERR_LambdaBindingMismatch1, ERRID.ERR_LambdaBindingMismatch2),
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
End If
If boundLambda Is Nothing Then
Debug.Assert(Conversions.NoConversion(convKind))
Dim errorRecovery As BoundLambda = unboundLambda.BindForErrorRecovery()
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, errorRecovery, convKind, False, isExplicit, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Dim boundLambdaDiagnostics = boundLambda.Diagnostics
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) >= boundLambda.DelegateRelaxation)
Debug.Assert(Conversions.ClassifyMethodConversionForLambdaOrAnonymousDelegate(delegateInvoke, boundLambda.LambdaSymbol, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) = MethodConversionKind.Identity OrElse
((convKind And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelNone AndAlso
boundLambda.MethodConversionKind <> MethodConversionKind.Identity))
Dim reportedAnError As Boolean = boundLambdaDiagnostics.Diagnostics.HasAnyErrors()
diagnostics.AddRange(boundLambdaDiagnostics)
Dim relaxationLambdaOpt As BoundLambda = Nothing
If (convKind And ConversionKind.DelegateRelaxationLevelMask) = ConversionKind.DelegateRelaxationLevelInvalid AndAlso
Not reportedAnError AndAlso Not boundLambda.HasErrors Then
' We don't try to infer return type of a lambda that has both Async and Iterator modifiers, let's suppress the
' signature mismatch error in this case.
If unboundLambda.ReturnType IsNot Nothing OrElse unboundLambda.Flags <> (SourceMemberFlags.Async Or SourceMemberFlags.Iterator) Then
Dim err As ERRID
If unboundLambda.IsFunctionLambda Then
err = ERRID.ERR_LambdaBindingMismatch1
Else
err = ERRID.ERR_LambdaBindingMismatch2
End If
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
err,
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
ElseIf Conversions.IsStubRequiredForMethodConversion(boundLambda.MethodConversionKind) Then
Debug.Assert(Conversions.IsDelegateRelaxationSupportedFor(boundLambda.MethodConversionKind))
' Need to produce a stub.
' First, we need to get an Anonymous Delegate of the same shape as the lambdaSymbol.
Dim lambdaSymbol As LambdaSymbol = boundLambda.LambdaSymbol
Dim anonymousDelegateType As NamedTypeSymbol = ConstructAnonymousDelegateSymbol(unboundLambda,
(lambdaSymbol.Parameters.As(Of BoundLambdaParameterSymbol)),
lambdaSymbol.ReturnType,
diagnostics)
' Second, reclassify the bound lambda as an instance of the Anonymous Delegate.
Dim anonymousDelegateInstance = New BoundConversion(tree, boundLambda, ConversionKind.Widening Or ConversionKind.Lambda,
False, False, anonymousDelegateType)
anonymousDelegateInstance.SetWasCompilerGenerated()
' Third, create a method group representing Invoke method of the instance of the Anonymous Delegate.
Dim methodGroup = New BoundMethodGroup(unboundLambda.Syntax,
Nothing,
ImmutableArray.Create(anonymousDelegateType.DelegateInvokeMethod),
LookupResultKind.Good,
anonymousDelegateInstance,
QualificationKind.QualifiedViaValue)
methodGroup.SetWasCompilerGenerated()
' Fourth, create a lambda with the shape of the target delegate that calls the Invoke with appropriate conversions
' and drops parameters and/or return value, if needed, thus performing the relaxation.
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
relaxationLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(unboundLambda.Syntax,
delegateInvoke,
methodGroup,
boundLambda.DelegateRelaxation,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression,
diagnostics:=diagnostics)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, boundLambda, convKind, False, isExplicit, Nothing,
If(relaxationLambdaOpt Is Nothing,
Nothing,
New BoundRelaxationLambda(tree, relaxationLambdaOpt, receiverPlaceholderOpt:=Nothing).MakeCompilerGenerated()),
targetType)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End Function
Private Function ReclassifyQueryLambdaExpression(
lambda As BoundQueryLambda,
conversionSemantics As SyntaxKind,
tree As SyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(lambda.Type Is Nothing)
' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim targetDelegateType As NamedTypeSymbol = targetType.DelegateOrExpressionDelegate(Me)
If Conversions.NoConversion(convKind) Then
If targetType.IsStrictSupertypeOfConcreteDelegate() AndAlso Not targetType.IsObjectType() Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotCreatableDelegate1, targetType)
Else
If targetDelegateType Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
Else
Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
If invoke Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
ElseIf Not ReportDelegateInvokeUseSite(diagnostics, lambda.Syntax, targetDelegateType, invoke) Then
' Conversion could fail because we couldn't convert body of the lambda
' to the target delegate type. We want to report that error instead of
' lambda signature mismatch.
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate AndAlso
Not invoke.IsSub AndAlso
Conversions.FailedDueToQueryLambdaBodyMismatch(convKind) Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax,
invoke.ReturnType,
lambda.Expression,
diagnostics,
If(invoke.ReturnType.IsBooleanType,
lambda.ExprIsOperandOfConditionalBranch,
False)),
exprIsOperandOfConditionalBranch:=False)
Else
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaBindingMismatch1, targetDelegateType)
End If
End If
End If
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Dim delegateInvoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
For Each delegateParam As ParameterSymbol In delegateInvoke.Parameters
If delegateParam.IsByRef OrElse delegateParam.OriginalDefinition.Type.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateParam.Type.IsRestrictedTypeOrArrayType(restrictedType) Then
ReportDiagnostic(diagnostics, lambda.LambdaSymbol.Parameters(delegateParam.Ordinal).Locations(0),
ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
Next
Dim delegateReturnType As TypeSymbol = delegateInvoke.ReturnType
If delegateInvoke.OriginalDefinition.ReturnType.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateReturnType.IsRestrictedTypeOrArrayType(restrictedType) Then
Dim location As SyntaxNode
If lambda.Expression.Kind = BoundKind.RangeVariableAssignment Then
location = DirectCast(lambda.Expression, BoundRangeVariableAssignment).Value.Syntax
Else
location = lambda.Expression.Syntax
End If
ReportDiagnostic(diagnostics, location, ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax, delegateReturnType, lambda.Expression,
diagnostics,
If(delegateReturnType.IsBooleanType(), lambda.ExprIsOperandOfConditionalBranch, False)),
exprIsOperandOfConditionalBranch:=False)
Else
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
lambda.Expression, exprIsOperandOfConditionalBranch:=False)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End Function
Private Function ReclassifyInterpolatedStringExpression(conversionSemantics As SyntaxKind, tree As SyntaxNode, convKind As ConversionKind, isExplicit As Boolean, node As BoundInterpolatedStringExpression, targetType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression
If (convKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString Then
Debug.Assert(targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_IFormattable)) OrElse targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_FormattableString)))
Return New BoundConversion(tree, node, ConversionKind.InterpolatedString, False, isExplicit, targetType)
End If
Return node
End Function
Private Function ReclassifyTupleLiteral(
convKind As ConversionKind,
tree As SyntaxNode,
isExplicit As Boolean,
sourceTuple As BoundTupleLiteral,
destination As TypeSymbol,
diagnostics As BindingDiagnosticBag) As BoundExpression
' We have a successful tuple conversion rather than producing a separate conversion node
' which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments.
Dim isNullableTupleConversion = (convKind And ConversionKind.Nullable) <> 0
Debug.Assert(Not isNullableTupleConversion OrElse destination.IsNullableType())
Dim targetType = destination
If isNullableTupleConversion Then
targetType = destination.GetNullableUnderlyingType()
End If
Dim arguments = sourceTuple.Arguments
If Not targetType.IsTupleOrCompatibleWithTupleOfCardinality(arguments.Length) Then
Return sourceTuple
End If
If targetType.IsTupleType Then
Dim destTupleType = DirectCast(targetType, TupleTypeSymbol)
TupleTypeSymbol.ReportNamesMismatchesIfAny(targetType, sourceTuple, diagnostics)
' do not lose the original element names in the literal if different from names in the target
' Come back to this, what about locations? (https:'github.com/dotnet/roslyn/issues/11013)
targetType = destTupleType.WithElementNames(sourceTuple.ArgumentNamesOpt)
End If
Dim convertedArguments = ArrayBuilder(Of BoundExpression).GetInstance(arguments.Length)
Dim targetElementTypes As ImmutableArray(Of TypeSymbol) = targetType.GetElementTypesOfTupleOrCompatible()
Debug.Assert(targetElementTypes.Length = arguments.Length, "converting a tuple literal to incompatible type?")
For i As Integer = 0 To arguments.Length - 1
Dim argument = arguments(i)
Dim destType = targetElementTypes(i)
convertedArguments.Add(ApplyConversion(argument.Syntax, destType, argument, isExplicit, diagnostics))
Next
Dim result As BoundExpression = New BoundConvertedTupleLiteral(
sourceTuple.Syntax,
sourceTuple.Type,
convertedArguments.ToImmutableAndFree(),
targetType)
If Not TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything) AndAlso convKind <> Nothing Then
' literal cast is applied to the literal
result = New BoundConversion(sourceTuple.Syntax, result, convKind, checked:=False, explicitCastInCode:=isExplicit, type:=destination)
End If
' If we had a cast in the code, keep conversion in the tree.
' even though the literal is already converted to the target type.
If isExplicit Then
result = New BoundConversion(
tree,
result,
ConversionKind.Identity,
checked:=False,
explicitCastInCode:=isExplicit,
type:=destination)
End If
Return result
End Function
Private Sub WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(
convKind As ConversionKind,
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag
)
If Conversions.IsNarrowingConversion(convKind) Then
Dim interfaceType As TypeSymbol = Nothing
Dim classType As NamedTypeSymbol = Nothing
If sourceType.IsInterfaceType() Then
If targetType.IsClassType() Then
interfaceType = sourceType
classType = DirectCast(targetType, NamedTypeSymbol)
End If
ElseIf sourceType.IsClassType() AndAlso targetType.IsInterfaceType() Then
interfaceType = targetType
classType = DirectCast(sourceType, NamedTypeSymbol)
End If
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If classType IsNot Nothing AndAlso
interfaceType IsNot Nothing AndAlso
classType.IsNotInheritable AndAlso
Not classType.IsComImport() AndAlso
Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(classType, interfaceType, useSiteInfo)) Then
' Report specific warning if converting IEnumerable(Of XElement) to String.
If (targetType.SpecialType = SpecialType.System_String) AndAlso IsIEnumerableOfXElement(sourceType, useSiteInfo) Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_UseValueForXmlExpression3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.WRN_InterfaceConversion2, sourceType, targetType)
End If
End If
diagnostics.AddDependencies(useSiteInfo)
End If
End Sub
Private Function IsIEnumerableOfXElement(type As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean
Return type.IsOrImplementsIEnumerableOfXElement(Compilation, useSiteInfo)
End Function
Private Sub ReportNoConversionError(
location As SyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
Optional copybackConversionParamName As String = Nothing
)
If sourceType.IsArrayType() AndAlso targetType.IsArrayType() Then
Dim sourceArray = DirectCast(sourceType, ArrayTypeSymbol)
Dim targetArray = DirectCast(targetType, ArrayTypeSymbol)
Dim sourceElement = sourceArray.ElementType
Dim targetElement = targetArray.ElementType
If sourceArray.Rank <> targetArray.Rank Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayRankMismatch2, sourceType, targetType)
ElseIf sourceArray.IsSZArray <> targetArray.IsSZArray Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
ElseIf Not (sourceElement.IsErrorType() OrElse targetElement.IsErrorType()) Then
Dim elemConv = Conversions.ClassifyDirectCastConversion(sourceElement, targetElement, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
If Not Conversions.IsIdentityConversion(elemConv) AndAlso
(targetElement.IsObjectType() OrElse targetElement.SpecialType = SpecialType.System_ValueType) AndAlso
Not sourceElement.IsReferenceType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertObjectArrayMismatch3, sourceType, targetType, sourceElement)
ElseIf Not Conversions.IsIdentityConversion(elemConv) AndAlso
Not (Conversions.IsWideningConversion(elemConv) AndAlso
(elemConv And (ConversionKind.Reference Or ConversionKind.Value Or ConversionKind.TypeParameter)) <> 0) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayMismatch4, sourceType, targetType, sourceElement, targetElement)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End If
ElseIf sourceType.IsDateTimeType() AndAlso targetType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DateToDoubleConversion)
ElseIf targetType.IsDateTimeType() AndAlso sourceType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DoubleToDateConversion)
ElseIf targetType.IsCharType() AndAlso sourceType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_IntegralToCharTypeMismatch1, sourceType)
ElseIf sourceType.IsCharType() AndAlso targetType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CharToIntegralTypeMismatch1, targetType)
ElseIf copybackConversionParamName IsNot Nothing Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CopyBackTypeMismatch3,
copybackConversionParamName, sourceType, targetType)
ElseIf sourceType.IsInterfaceType() AndAlso targetType.IsValueType() AndAlso IsIEnumerableOfXElement(sourceType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatchForXml3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/VisualBasic/Portable/GenerateMember/GenerateParameterizedMember/VisualBasicGenerateConversionService.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.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod
<ExportLanguageService(GetType(IGenerateConversionService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicGenerateConversionService
Inherits AbstractGenerateConversionService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel)
End Function
Protected Overrides Function CreateInvocationMethodInfo(document As SemanticDocument, abstractState As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As AbstractInvocationInfo
Return New VisualBasicGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService).InvocationExpressionInfo(document, abstractState)
End Function
Protected Overrides Function IsExplicitConversionGeneration(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsImplicitConversionGeneration(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax AndAlso
Not IsExplicitConversionGeneration(node) AndAlso
Not IsInMemberAccessExpression(node) AndAlso
Not IsInImplementsClause(node)
End Function
Private Shared Function IsInImplementsClause(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.ImplementsClause)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Private Shared Function IsInMemberAccessExpression(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel)
End Function
Protected Overrides Function TryInitializeExplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.NarrowingKeyword,
WellKnownMemberNames.ExplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Protected Overrides Function TryInitializeImplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.WideningKeyword,
WellKnownMemberNames.ImplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Private Shared Function TryGetConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
Dim castExpression = TryCast(expression.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(expression.Span)).FirstOrDefault, CastExpressionSyntax)
If castExpression IsNot Nothing Then
Return TryGetExplicitConversionMethodAndTypeToGenerateIn(
document,
castExpression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
expression = TryCast(expression.AncestorsAndSelf.Where(Function(n) TypeOf n Is ExpressionSyntax And n.Span.Contains(expression.Span)).FirstOrDefault, ExpressionSyntax)
If expression IsNot Nothing Then
Return TryGetImplicitConversionMethodAndTypeToGenerateIn(
document,
expression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
Return False
End Function
Private Shared Function IsCastExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is DirectCastExpressionSyntax OrElse TypeOf node Is CTypeExpressionSyntax OrElse TypeOf node Is TryCastExpressionSyntax
End Function
Private Shared Function TryGetExplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, castExpression As CastExpressionSyntax, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(typeToGenerateIn, True, classInterfaceModuleStructTypes) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Shared Function TryGetImplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(typeToGenerateIn, True, classInterfaceModuleStructTypes) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Shared Function GenerateMethodSymbol(typeToGenerateIn As INamedTypeSymbol, parameterSymbol As INamedTypeSymbol) As IMethodSymbol
If typeToGenerateIn.IsGenericType Then
typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType.ConstructedFrom
End If
Return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes:=ImmutableArray(Of AttributeData).Empty,
accessibility:=Nothing,
modifiers:=Nothing,
returnType:=typeToGenerateIn,
refKind:=RefKind.None,
explicitInterfaceImplementations:=Nothing,
name:=Nothing,
typeParameters:=ImmutableArray(Of ITypeParameterSymbol).Empty,
parameters:=ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v")),
statements:=Nothing,
handlesExpressions:=Nothing,
returnTypeAttributes:=Nothing,
methodKind:=MethodKind.Conversion)
End Function
Protected Overrides Function GetExplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_narrowing_conversion_in_0, state.TypeToGenerateIn.Name)
End Function
Protected Overrides Function GetImplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_widening_conversion_in_0, state.TypeToGenerateIn.Name)
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.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod
<ExportLanguageService(GetType(IGenerateConversionService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicGenerateConversionService
Inherits AbstractGenerateConversionService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel)
End Function
Protected Overrides Function CreateInvocationMethodInfo(document As SemanticDocument, abstractState As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As AbstractInvocationInfo
Return New VisualBasicGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService).InvocationExpressionInfo(document, abstractState)
End Function
Protected Overrides Function IsExplicitConversionGeneration(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsImplicitConversionGeneration(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax AndAlso
Not IsExplicitConversionGeneration(node) AndAlso
Not IsInMemberAccessExpression(node) AndAlso
Not IsInImplementsClause(node)
End Function
Private Shared Function IsInImplementsClause(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.ImplementsClause)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Private Shared Function IsInMemberAccessExpression(node As SyntaxNode) As Boolean
Return node.AncestorsAndSelf.Where(Function(n) n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).Where(Function(n) n.Span.Contains(node.Span)).Any
End Function
Protected Overrides Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean
Return VisualBasicCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel)
End Function
Protected Overrides Function TryInitializeExplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.NarrowingKeyword,
WellKnownMemberNames.ExplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Protected Overrides Function TryInitializeImplicitConversionState(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
If TryGetConversionMethodAndTypeToGenerateIn(document, expression, classInterfaceModuleStructTypes, cancellationToken, methodSymbol, typeToGenerateIn) Then
identifierToken = SyntaxFactory.Token(
SyntaxKind.WideningKeyword,
WellKnownMemberNames.ImplicitConversionName)
Return True
End If
identifierToken = Nothing
methodSymbol = Nothing
typeToGenerateIn = Nothing
Return False
End Function
Private Shared Function TryGetConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
Dim castExpression = TryCast(expression.AncestorsAndSelf.Where(AddressOf IsCastExpression).Where(Function(n) n.Span.Contains(expression.Span)).FirstOrDefault, CastExpressionSyntax)
If castExpression IsNot Nothing Then
Return TryGetExplicitConversionMethodAndTypeToGenerateIn(
document,
castExpression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
expression = TryCast(expression.AncestorsAndSelf.Where(Function(n) TypeOf n Is ExpressionSyntax And n.Span.Contains(expression.Span)).FirstOrDefault, ExpressionSyntax)
If expression IsNot Nothing Then
Return TryGetImplicitConversionMethodAndTypeToGenerateIn(
document,
expression,
classInterfaceModuleStructTypes,
cancellationToken,
methodSymbol,
typeToGenerateIn)
End If
Return False
End Function
Private Shared Function IsCastExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is DirectCastExpressionSyntax OrElse TypeOf node Is CTypeExpressionSyntax OrElse TypeOf node Is TryCastExpressionSyntax
End Function
Private Shared Function TryGetExplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, castExpression As CastExpressionSyntax, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Type, cancellationToken).Type, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(castExpression.Expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(typeToGenerateIn, True, classInterfaceModuleStructTypes) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Shared Function TryGetImplicitConversionMethodAndTypeToGenerateIn(document As SemanticDocument, expression As SyntaxNode, classInterfaceModuleStructTypes As ISet(Of TypeKind), cancellationToken As CancellationToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean
methodSymbol = Nothing
typeToGenerateIn = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType, INamedTypeSymbol)
Dim parameterSymbol = TryCast(document.SemanticModel.GetTypeInfo(expression, cancellationToken).Type, INamedTypeSymbol)
If typeToGenerateIn Is Nothing OrElse parameterSymbol Is Nothing OrElse typeToGenerateIn.IsErrorType OrElse parameterSymbol.IsErrorType Then
Return False
End If
methodSymbol = GenerateMethodSymbol(typeToGenerateIn, parameterSymbol)
If Not ValidateTypeToGenerateIn(typeToGenerateIn, True, classInterfaceModuleStructTypes) Then
typeToGenerateIn = parameterSymbol
End If
Return True
End Function
Private Shared Function GenerateMethodSymbol(typeToGenerateIn As INamedTypeSymbol, parameterSymbol As INamedTypeSymbol) As IMethodSymbol
If typeToGenerateIn.IsGenericType Then
typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType.ConstructedFrom
End If
Return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes:=ImmutableArray(Of AttributeData).Empty,
accessibility:=Nothing,
modifiers:=Nothing,
returnType:=typeToGenerateIn,
refKind:=RefKind.None,
explicitInterfaceImplementations:=Nothing,
name:=Nothing,
typeParameters:=ImmutableArray(Of ITypeParameterSymbol).Empty,
parameters:=ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v")),
statements:=Nothing,
handlesExpressions:=Nothing,
returnTypeAttributes:=Nothing,
methodKind:=MethodKind.Conversion)
End Function
Protected Overrides Function GetExplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_narrowing_conversion_in_0, state.TypeToGenerateIn.Name)
End Function
Protected Overrides Function GetImplicitConversionDisplayText(state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateConversionService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As String
Return String.Format(VBFeaturesResources.Generate_widening_conversion_in_0, state.TypeToGenerateIn.Name)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/MSBuildTest/Interop.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Setup.Configuration;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
internal static class Interop
{
private const int REGDG_E_CLASSNOTREG = unchecked((int)0x80040154);
[DllImport("Microsoft.VisualStudio.Setup.Configuration.Native.dll", ExactSpelling = true, PreserveSig = true)]
private static extern int GetSetupConfiguration(
[MarshalAs(UnmanagedType.Interface), Out] out ISetupConfiguration configuration,
IntPtr reserved);
public static ISetupConfiguration2 GetSetupConfiguration()
{
try
{
return new SetupConfiguration();
}
catch (COMException ex) when (ex.ErrorCode == REGDG_E_CLASSNOTREG)
{
// We could not CoCreate the SetupConfiguration object. If that fails, try p/invoking.
var hresult = GetSetupConfiguration(out var configuration, IntPtr.Zero);
if (hresult < 0)
{
throw new COMException($"Failed to get {nameof(ISetupConfiguration)}", hresult);
}
return configuration as ISetupConfiguration2;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Setup.Configuration;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
internal static class Interop
{
private const int REGDG_E_CLASSNOTREG = unchecked((int)0x80040154);
[DllImport("Microsoft.VisualStudio.Setup.Configuration.Native.dll", ExactSpelling = true, PreserveSig = true)]
private static extern int GetSetupConfiguration(
[MarshalAs(UnmanagedType.Interface), Out] out ISetupConfiguration configuration,
IntPtr reserved);
public static ISetupConfiguration2 GetSetupConfiguration()
{
try
{
return new SetupConfiguration();
}
catch (COMException ex) when (ex.ErrorCode == REGDG_E_CLASSNOTREG)
{
// We could not CoCreate the SetupConfiguration object. If that fails, try p/invoking.
var hresult = GetSetupConfiguration(out var configuration, IntPtr.Zero);
if (hresult < 0)
{
throw new COMException($"Failed to get {nameof(ISetupConfiguration)}", hresult);
}
return configuration as ISetupConfiguration2;
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class CSharp
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "namespace [|N1|] { }";
var expected = @"namespace N1 {
namespace N2
{
}
}";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int F;
}";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
private static string F;
}";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int[] F;
}";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe int F;
}";
await TestAddFieldAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddFieldToCompilationUnit()
{
var input = "";
var expected = "public int F;\n";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)), addToCompilationUnit: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public C()
{
}
}";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public C();
}";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "class [|C|] { }";
var expected = @"using System;
class C
{
public C(DateTime dt, int i)
{
}
}";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(DateTime), "dt"), Parameter(typeof(int), "i")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "class [|C|] { public C(int i) { } }";
var expected = "class C { public C() : this(42) { } public C(int i) { } }";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(CS.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticConstructor()
{
var input = "class [|C|] { }";
var expected = @"class C
{
static C()
{
}
}";
await TestAddConstructorAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544082")]
public async Task AddClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class C
{
}
}";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class @class
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class classæøå
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "classæøå");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddStaticClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public static class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddSealedClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
private sealed class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Private,
modifiers: new Editing.DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddAbstractClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
protected internal abstract class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
modifiers: new Editing.DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStruct()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
internal struct S
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStruct()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public struct S
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "S",
modifiers: new Editing.DeclarationModifiers(isSealed: true),
accessibility: Accessibility.Public,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public interface I
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")]
public async Task AddEnum()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public enum E
{
}
}";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public enum E
{
F1 = 1,
F2 = 2
}
}";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")]
public async Task AddDelegateType()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public delegate int D(string s);
}";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public delegate int D(string s);
}";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")),
modifiers: new Editing.DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public event System.Action E;
}";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeEvent()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe event System.Action E;
}";
await TestAddEventAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public event System.Action E
{
add
{
}
remove
{
}
}
}";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public void M()
{
}
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "class [|C|] { }";
var expected = @"using System;
class C
{
public DateTime @static()
{
}
}";
await TestAddMethodAsync(input, expected,
name: "static",
returnType: typeof(DateTime));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticMethodToStruct()
{
var input = "struct [|S|] { }";
var expected = @"struct S
{
public static int M()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSealedOverrideMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public sealed override int GetHashCode()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new Editing.DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAbstractMethod()
{
var input = "abstract class [|C|] { }";
var expected = @"abstract class C
{
public abstract int M();
}";
await TestAddMethodAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isAbstract: true),
returnType: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int M();
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int M<T>()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "return new T().GetHashCode();");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
protected virtual int M()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new Editing.DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeNewMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe new string ToString()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
name: "ToString",
modifiers: new Editing.DeclarationModifiers(isNew: true, isUnsafe: true),
returnType: typeof(string),
statements: "return String.Empty;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementationOfUnsafeMethod()
{
var input = "interface I { unsafe void M(int i); } class [|C|] : I { }";
var expected = @"interface I { unsafe void M(int i); }
class C : I
{
unsafe void I.M(int i)
{
}
}";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "interface I { void M(int i); } class [|C|] : I { }";
var expected = @"interface I { void M(int i); }
class C : I
{
void I.M(int i)
{
}
}";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator true(C other)
{
$$
}
public static bool operator false(C other)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "return false;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator +(C other)
{
$$
}
public static object operator -(C other)
{
$$
}
public static object operator !(C other)
{
$$
}
public static object operator ~(C other)
{
$$
}
public static object operator ++(C other)
{
$$
}
public static object operator --(C other)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot,
CodeGenerationOperatorKind.OnesComplement,
CodeGenerationOperatorKind.Increment,
CodeGenerationOperatorKind.Decrement
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "return null;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator +(C a, C b)
{
$$
}
public static object operator -(C a, C b)
{
$$
}
public static object operator *(C a, C b)
{
$$
}
public static object operator /(C a, C b)
{
$$
}
public static object operator %(C a, C b)
{
$$
}
public static object operator &(C a, C b)
{
$$
}
public static object operator |(C a, C b)
{
$$
}
public static object operator ^(C a, C b)
{
$$
}
public static object operator <<(C a, C b)
{
$$
}
public static object operator >>(C a, C b)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "return null;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator ==(C a, C b)
{
$$
}
public static bool operator !=(C a, C b)
{
$$
}
public static bool operator <(C a, C b)
{
$$
}
public static bool operator >(C a, C b)
{
$$
}
public static bool operator <=(C a, C b)
{
$$
}
public static bool operator >=(C a, C b)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.LessThanOrEqual,
CodeGenerationOperatorKind.GreaterThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "class [|C|] { }";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Like,
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C
{
public static explicit operator int(C other)
{
$$
}
}";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C
{
public static implicit operator int(C other)
{
$$
}
}";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatements()
{
var input = "class C { public void [|M|]() { Console.WriteLine(1); } }";
var expected = "class C { public void M() { Console.WriteLine(1); $$} }";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2);");
}
[WorkItem(840265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithNonDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(string text =\"Hello\") { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(string), "text", true, "Hello")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(double number =0) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(double), "number", true)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(int num, string text =\"Hello!\", float floating =0.5F) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5f)));
}
[WorkItem(841365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/841365")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParamsParameterToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(params char[]characters) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(char[]), "characters", isParams: true)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544015")]
public async Task AddAutoProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int P { get; internal set; }
}";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
setterAccessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeAutoProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe int P { get; internal set; }
}";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
setterAccessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer1()
{
var input = "class [|C|] { }";
var expected = "class C { public string this[int i] => String.Empty; }";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "return String.Empty;",
isIndexer: true,
codeGenerationOptions: new CodeGenerationOptions(parseOptions: CSharpParseOptions.Default));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer2()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public string this[int i]
{
get
{
$$
}
}
}";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "return String.Empty;",
isIndexer: true,
options: new Dictionary<OptionKey2, object> {
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParameterfulProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public string get_P(int i, int j)
{
$$
}
public void set_P(int i, int j, string value)
{
}
}";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
getStatements: "return String.Empty;",
setStatements: "",
parameters: Parameters(Parameter(typeof(int), "i"), Parameter(typeof(int), "j")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "class [|C|] { }";
var expected = @"[System.Serializable]
class C { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"[System.Serializable] class [|C|] { }";
var expected = "class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "class C { public void [|M()|] { } }";
var expected = "class C {[System.Serializable] public void M() { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = "class C { [System.Serializable] public void [|M()|] { } }";
var expected = "class C { public void M() { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "class C { [|public int F|]; }";
var expected = "class C {[System.Serializable] public int F; }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = "class C { [System.Serializable] public int [|F|]; }";
var expected = "class C { public int F; }";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "class C { public int [|P|] { get; set; }}";
var expected = "class C {[System.Serializable] public int P { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = "class C { [System.Serializable] public int [|P|] { get; set; }}";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "class C { public int P { [|get|]; set; }}";
var expected = "class C { public int P { [System.Serializable] get; set; }}";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = "class C { public int P { [System.Serializable] [|get|]; set; } }";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "enum [|C|] { One, Two }";
var expected = @"[System.Serializable]
enum C { One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = "[System.Serializable] enum [|C|] { One, Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "enum C { [|One|], Two }";
var expected = "enum C {[System.Serializable] One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = "enum C { [System.Serializable] [|One|], Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToIndexer()
{
var input = "class C { public int [|this[int y]|] { get; set; }}";
var expected = "class C {[System.Serializable] public int this[int y] { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromIndexer()
{
var input = "class C { [System.Serializable] public int [|this[int y]|] { get; set; }}";
var expected = "class C { public int this[int y] { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "class C { public static C operator [|+|] (C c1, C c2) { return new C(); }}";
var expected = "class C {[System.Serializable] public static C operator +(C c1, C c2) { return new C(); } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = "class C { [System.Serializable] public static C operator [|+|](C c1, C c2) { return new C(); }}";
var expected = "class C { public static C operator +(C c1, C c2) { return new C(); } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "delegate int [|D()|];";
var expected = @"[System.Serializable]
delegate int D();";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = "[System.Serializable] delegate int [|D()|];";
var expected = "delegate int D();";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "class C { public void M([|int x|]) { } }";
var expected = "class C { public void M([System.Serializable] int x) { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = "class C { public void M([System.Serializable] [|int x|]) { } }";
var expected = "class C { public void M(int x) { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypeParam()
{
var input = "class C<[|T|]> { }";
var expected = "class C<[System.Serializable] T> { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypeParam()
{
var input = "class C<[System.Serializable] [|T|]> { }";
var expected = "class C<T> { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|class C { } class D {} |]";
var expected = @"[assembly: System.Serializable]
class C { }
class D { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|class C { } class D {} |]";
var expected = "";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.RefKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"// Comment 1
[System.Serializable] // Comment 2
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"// Comment 1
[System.Serializable]
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"internal partial sealed class C // Comment 1
{
// Comment 2
}";
var eol = SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { SyntaxFactory.Token(SyntaxKind.InternalKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new Editing.DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.CSharp));
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"// Comment 0
public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"// Comment 0
internal static class C // Comment 1
{
// Comment 2
}";
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, accessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
public static class C
{
// Comment 1
public static char [|F|]() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 1
public static int F() { return 0; }
}";
await TestUpdateDeclarationAsync<MethodDeclarationSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int {|RetainedMember:f|};
// Comment 1
public static char F() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 0
public int f;
public int f2;
}";
var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(
input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers_DifferentOrder()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int f;
// Comment 1
public static char {|RetainedMember:F|}() { return 0; }
}";
var expected = @"
public static class C
{
public int f2;
// Comment 1
public static char F() { return 0; }
}";
var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, getNewMembers: getMembers, declareNewMembersAtTop: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortAroundDestructor()
{
var generationSource = "public class [|C|] { public C(){} public int this[int index]{get{return 0;}set{value = 0;}} }";
var initial = "public class [|C|] { ~C(){} }";
var expected = @"public class C {
public C()
{
}
~C(){}
public int this[int index]
{
get
{
}
set
{
}
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
namespace N
{
public class [|C|]
{
// Unary operators
public static bool operator false (C other) { return false; }
public static bool operator true (C other) { return true; }
public static C operator ++ (C other) { return null; }
public static C operator -- (C other) { return null; }
public static C operator ~ (C other) { return null; }
public static C operator ! (C other) { return null; }
public static C operator - (C other) { return null; }
public static C operator + (C other) { return null; }
// Binary operators
public static C operator >> (C a, int shift) { return null; }
public static C operator << (C a, int shift) { return null; }
public static C operator ^ (C a, C b) { return null; }
public static C operator | (C a, C b) { return null; }
public static C operator & (C a, C b) { return null; }
public static C operator % (C a, C b) { return null; }
public static C operator / (C a, C b) { return null; }
public static C operator * (C a, C b) { return null; }
public static C operator - (C a, C b) { return null; }
public static C operator + (C a, C b) { return null; }
// Comparison operators
public static bool operator >= (C a, C b) { return true; }
public static bool operator <= (C a, C b) { return true; }
public static bool operator > (C a, C b) { return true; }
public static bool operator < (C a, C b) { return true; }
public static bool operator != (C a, C b) { return true; }
public static bool operator == (C a, C b) { return true; }
}
}";
var initial = "namespace [|N|] { }";
var expected = @"namespace N
{
public class C
{
public static C operator +(C other);
public static C operator +(C a, C b);
public static C operator -(C other);
public static C operator -(C a, C b);
public static C operator !(C other);
public static C operator ~(C other);
public static C operator ++(C other);
public static C operator --(C other);
public static C operator *(C a, C b);
public static C operator /(C a, C b);
public static C operator %(C a, C b);
public static C operator &(C a, C b);
public static C operator |(C a, C b);
public static C operator ^(C a, C b);
public static C operator <<(C a, int shift);
public static C operator >>(C a, int shift);
public static bool operator ==(C a, C b);
public static bool operator !=(C a, C b);
public static bool operator <(C a, C b);
public static bool operator >(C a, C b);
public static bool operator <=(C a, C b);
public static bool operator >=(C a, C b);
public static bool operator true(C other);
public static bool operator false(C other);
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.CSharp,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
}
[WorkItem(665008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665008")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestExtensionMethods()
{
var generationSource = @"
public static class [|C|]
{
public static void ExtMethod1(this string s, int y, string z) {}
}";
var initial = "public static class [|C|] {}";
var expected = @"public static class C
{
public static void ExtMethod1(this string s, int y, string z);
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(530829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestVBPropertiesWithParams()
{
var generationSource = @"
Namespace N
Public Class [|C|]
Public Overridable Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class
End Namespace
";
var initial = "namespace [|N|] {}";
var expected = @"namespace N
{
public class C
{
public virtual string get_IndexProp(int p1);
public virtual void set_IndexProp(int p1, string value);
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(812738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812738")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestRefParamsWithDefaultValue()
{
var generationSource = @"
Public Class [|C|]
Public Sub Goo(x As Integer, Optional ByRef y As Integer = 10, Optional ByRef z As Object = Nothing)
End Sub
End Class";
var initial = "public class [|C|] {}";
var expected = @"public class C
{
public void Goo(int x, ref int y, ref object z);
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
namespace N
{
public class [|C|]<T, U> where T : struct where U : class
{
public void Goo<Q, R>() where Q : new() where R : IComparable { }
public delegate void D<T, U>(T t, U u) where T : struct where U : class;
}
}
";
var initial = "namespace [|N|] {}";
var expected = @"namespace N
{
public class C<T, U>
where T : struct
where U : class
{
public void Goo<Q, R>()
where Q : new()
where R : IComparable;
public delegate void D<T, U>(T t, U u)
where T : struct
where U : class;
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class CSharp
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "namespace [|N1|] { }";
var expected = @"namespace N1 {
namespace N2
{
}
}";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int F;
}";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
private static string F;
}";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int[] F;
}";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeField()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe int F;
}";
await TestAddFieldAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddFieldToCompilationUnit()
{
var input = "";
var expected = "public int F;\n";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)), addToCompilationUnit: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public C()
{
}
}";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public C();
}";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "class [|C|] { }";
var expected = @"using System;
class C
{
public C(DateTime dt, int i)
{
}
}";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(DateTime), "dt"), Parameter(typeof(int), "i")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "class [|C|] { public C(int i) { } }";
var expected = "class C { public C() : this(42) { } public C(int i) { } }";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(CS.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticConstructor()
{
var input = "class [|C|] { }";
var expected = @"class C
{
static C()
{
}
}";
await TestAddConstructorAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544082")]
public async Task AddClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class C
{
}
}";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class @class
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public class classæøå
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "classæøå");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddStaticClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public static class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddSealedClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
private sealed class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Private,
modifiers: new Editing.DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544405")]
public async Task AddAbstractClass()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
protected internal abstract class C
{
}
}";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
modifiers: new Editing.DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStruct()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
internal struct S
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStruct()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public struct S
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "S",
modifiers: new Editing.DeclarationModifiers(isSealed: true),
accessibility: Accessibility.Public,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public interface I
{
}
}";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")]
public async Task AddEnum()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public enum E
{
}
}";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "namespace [|N|] { }";
var expected = @"namespace N
{
public enum E
{
F1 = 1,
F2 = 2
}
}";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544080")]
public async Task AddDelegateType()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public delegate int D(string s);
}";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public delegate int D(string s);
}";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")),
modifiers: new Editing.DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public event System.Action E;
}";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddCustomEventToClassFromSourceSymbol()
{
var sourceGenerated = @"class [|C2|]
{
event EventHandler Click
{
add
{
Events.AddHandler(""ClickEvent"", value)
}
remove
{
Events.RemoveHandler(""ClickEvent"", value)
}
}
}";
var input = "class [|C1|] { }";
var expected = @"class C1
{
event EventHandler Click
{
add
{
Events.AddHandler(""ClickEvent"", value)
}
remove
{
Events.RemoveHandler(""ClickEvent"", value)
}
}
}";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeEvent()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe event System.Action E;
}";
await TestAddEventAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public event System.Action E
{
add
{
}
remove
{
}
}
}";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public void M()
{
}
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassFromSourceSymbol()
{
var sourceGenerated = @"class [|C2|]
{
public int FInt()
{
return 0;
}
}";
var input = "class [|C1|] { }";
var expected = @"class C1
{
public int FInt()
{
return 0;
}
}";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "class [|C|] { }";
var expected = @"using System;
class C
{
public DateTime @static()
{
}
}";
await TestAddMethodAsync(input, expected,
name: "static",
returnType: typeof(DateTime));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStaticMethodToStruct()
{
var input = "struct [|S|] { }";
var expected = @"struct S
{
public static int M()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSealedOverrideMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public sealed override int GetHashCode()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new Editing.DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAbstractMethod()
{
var input = "abstract class [|C|] { }";
var expected = @"abstract class C
{
public abstract int M();
}";
await TestAddMethodAsync(input, expected,
modifiers: new Editing.DeclarationModifiers(isAbstract: true),
returnType: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int M();
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int M<T>()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "return new T().GetHashCode();");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
protected virtual int M()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new Editing.DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeNewMethod()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe new string ToString()
{
$$
}
}";
await TestAddMethodAsync(input, expected,
name: "ToString",
modifiers: new Editing.DeclarationModifiers(isNew: true, isUnsafe: true),
returnType: typeof(string),
statements: "return String.Empty;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementationOfUnsafeMethod()
{
var input = "interface I { unsafe void M(int i); } class [|C|] : I { }";
var expected = @"interface I { unsafe void M(int i); }
class C : I
{
unsafe void I.M(int i)
{
}
}";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "interface I { void M(int i); } class [|C|] : I { }";
var expected = @"interface I { void M(int i); }
class C : I
{
void I.M(int i)
{
}
}";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator true(C other)
{
$$
}
public static bool operator false(C other)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "return false;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator +(C other)
{
$$
}
public static object operator -(C other)
{
$$
}
public static object operator !(C other)
{
$$
}
public static object operator ~(C other)
{
$$
}
public static object operator ++(C other)
{
$$
}
public static object operator --(C other)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot,
CodeGenerationOperatorKind.OnesComplement,
CodeGenerationOperatorKind.Increment,
CodeGenerationOperatorKind.Decrement
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "return null;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static object operator +(C a, C b)
{
$$
}
public static object operator -(C a, C b)
{
$$
}
public static object operator *(C a, C b)
{
$$
}
public static object operator /(C a, C b)
{
$$
}
public static object operator %(C a, C b)
{
$$
}
public static object operator &(C a, C b)
{
$$
}
public static object operator |(C a, C b)
{
$$
}
public static object operator ^(C a, C b)
{
$$
}
public static object operator <<(C a, C b)
{
$$
}
public static object operator >>(C a, C b)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "return null;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
class [|C|]
{
}";
var expected = @"
class C
{
public static bool operator ==(C a, C b)
{
$$
}
public static bool operator !=(C a, C b)
{
$$
}
public static bool operator <(C a, C b)
{
$$
}
public static bool operator >(C a, C b)
{
$$
}
public static bool operator <=(C a, C b)
{
$$
}
public static bool operator >=(C a, C b)
{
$$
}
}";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.LessThanOrEqual,
CodeGenerationOperatorKind.GreaterThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "class [|C|] { }";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Like,
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "return true;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C
{
public static explicit operator int(C other)
{
$$
}
}";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = @"class [|C|] { }";
var expected = @"class C
{
public static implicit operator int(C other)
{
$$
}
}";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "return 0;");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatements()
{
var input = "class C { public void [|M|]() { Console.WriteLine(1); } }";
var expected = "class C { public void M() { Console.WriteLine(1); $$} }";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2);");
}
[WorkItem(840265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithNonDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(string text =\"Hello\") { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(string), "text", true, "Hello")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddDefaultParameterWithDefaultValueToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(double number =0) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(double), "number", true)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(int num, string text =\"Hello!\", float floating =0.5F) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5f)));
}
[WorkItem(841365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/841365")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParamsParameterToMethod()
{
var input = "class C { public void [|M|]() { } }";
var expected = "class C { public void M(params char[]characters) { } }";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(char[]), "characters", isParams: true)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544015")]
public async Task AddAutoProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public int P { get; internal set; }
}";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
setterAccessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsafeAutoProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public unsafe int P { get; internal set; }
}";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
modifiers: new Editing.DeclarationModifiers(isUnsafe: true),
setterAccessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyToClassFromSourceSymbol()
{
var sourceGenerated = @"class [|C2|]
{
public int P
{
get
{
return 0;
}
}
}";
var input = "class [|C1|] { }";
var expected = @"class C1
{
public int P
{
get
{
return 0;
}
}
}";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer1()
{
var input = "class [|C|] { }";
var expected = "class C { public string this[int i] => String.Empty; }";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "return String.Empty;",
isIndexer: true,
codeGenerationOptions: new CodeGenerationOptions(parseOptions: CSharpParseOptions.Default));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer2()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public string this[int i]
{
get
{
$$
}
}
}";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "return String.Empty;",
isIndexer: true,
options: new Dictionary<OptionKey2, object> {
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParameterfulProperty()
{
var input = "class [|C|] { }";
var expected = @"class C
{
public string get_P(int i, int j)
{
$$
}
public void set_P(int i, int j, string value)
{
}
}";
await TestAddPropertyAsync(input, expected,
type: typeof(string),
getStatements: "return String.Empty;",
setStatements: "",
parameters: Parameters(Parameter(typeof(int), "i"), Parameter(typeof(int), "j")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "class [|C|] { }";
var expected = @"[System.Serializable]
class C { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"[System.Serializable] class [|C|] { }";
var expected = "class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "class C { public void [|M()|] { } }";
var expected = "class C {[System.Serializable] public void M() { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = "class C { [System.Serializable] public void [|M()|] { } }";
var expected = "class C { public void M() { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "class C { [|public int F|]; }";
var expected = "class C {[System.Serializable] public int F; }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = "class C { [System.Serializable] public int [|F|]; }";
var expected = "class C { public int F; }";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "class C { public int [|P|] { get; set; }}";
var expected = "class C {[System.Serializable] public int P { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = "class C { [System.Serializable] public int [|P|] { get; set; }}";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "class C { public int P { [|get|]; set; }}";
var expected = "class C { public int P { [System.Serializable] get; set; }}";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = "class C { public int P { [System.Serializable] [|get|]; set; } }";
var expected = "class C { public int P { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "enum [|C|] { One, Two }";
var expected = @"[System.Serializable]
enum C { One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = "[System.Serializable] enum [|C|] { One, Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "enum C { [|One|], Two }";
var expected = "enum C {[System.Serializable] One, Two }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = "enum C { [System.Serializable] [|One|], Two }";
var expected = "enum C { One, Two }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToIndexer()
{
var input = "class C { public int [|this[int y]|] { get; set; }}";
var expected = "class C {[System.Serializable] public int this[int y] { get; set; } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromIndexer()
{
var input = "class C { [System.Serializable] public int [|this[int y]|] { get; set; }}";
var expected = "class C { public int this[int y] { get; set; } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "class C { public static C operator [|+|] (C c1, C c2) { return new C(); }}";
var expected = "class C {[System.Serializable] public static C operator +(C c1, C c2) { return new C(); } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = "class C { [System.Serializable] public static C operator [|+|](C c1, C c2) { return new C(); }}";
var expected = "class C { public static C operator +(C c1, C c2) { return new C(); } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "delegate int [|D()|];";
var expected = @"[System.Serializable]
delegate int D();";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = "[System.Serializable] delegate int [|D()|];";
var expected = "delegate int D();";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "class C { public void M([|int x|]) { } }";
var expected = "class C { public void M([System.Serializable] int x) { } }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = "class C { public void M([System.Serializable] [|int x|]) { } }";
var expected = "class C { public void M(int x) { } }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypeParam()
{
var input = "class C<[|T|]> { }";
var expected = "class C<[System.Serializable] T> { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypeParam()
{
var input = "class C<[System.Serializable] [|T|]> { }";
var expected = "class C<T> { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|class C { } class D {} |]";
var expected = @"[assembly: System.Serializable]
class C { }
class D { }";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|class C { } class D {} |]";
var expected = "";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), SyntaxFactory.Token(SyntaxKind.RefKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"// Comment 1
[System.Serializable] // Comment 2
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"// Comment 1
[System.Serializable]
/* Comment 3*/ class [|C|] { }";
var expected = @"// Comment 1
/* Comment 3*/ class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
/* Comment 8*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attributes.
var input = @"// Comment 1
/*Comment2*/[ /*Comment3*/ System.Serializable /*Comment4*/, /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class [|C|] { }";
var expected = @"// Comment 1
/*Comment2*/[ /*Comment3*/ /*Comment5*/System.Flags /*Comment6*/] /*Comment7*/
[ /*Comment9*/ System.Obsolete /*Comment10*/] /*Comment11*/
/* Comment12*/
class C { }";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"internal partial sealed class C // Comment 1
{
// Comment 2
}";
var eol = SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { SyntaxFactory.Token(SyntaxKind.InternalKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new Editing.DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.CSharp));
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"// Comment 0
public static class [|C|] // Comment 1
{
// Comment 2
}";
var expected = @"// Comment 0
internal static class C // Comment 1
{
// Comment 2
}";
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, accessibility: Accessibility.Internal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
public static class C
{
// Comment 1
public static char [|F|]() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 1
public static int F() { return 0; }
}";
await TestUpdateDeclarationAsync<MethodDeclarationSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int {|RetainedMember:f|};
// Comment 1
public static char F() { return 0; }
}";
var expected = @"
public static class C
{
// Comment 0
public int f;
public int f2;
}";
var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(
input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers_DifferentOrder()
{
var input = @"
public static class [|C|]
{
// Comment 0
public int f;
// Comment 1
public static char {|RetainedMember:F|}() { return 0; }
}";
var expected = @"
public static class C
{
public int f2;
// Comment 1
public static char F() { return 0; }
}";
var getField = CreateField(Accessibility.Public, new Editing.DeclarationModifiers(), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassDeclarationSyntax>(input, expected, getNewMembers: getMembers, declareNewMembersAtTop: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortAroundDestructor()
{
var generationSource = "public class [|C|] { public C(){} public int this[int index]{get{return 0;}set{value = 0;}} }";
var initial = "public class [|C|] { ~C(){} }";
var expected = @"public class C {
public C()
{
}
~C(){}
public int this[int index]
{
get
{
}
set
{
}
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
namespace N
{
public class [|C|]
{
// Unary operators
public static bool operator false (C other) { return false; }
public static bool operator true (C other) { return true; }
public static C operator ++ (C other) { return null; }
public static C operator -- (C other) { return null; }
public static C operator ~ (C other) { return null; }
public static C operator ! (C other) { return null; }
public static C operator - (C other) { return null; }
public static C operator + (C other) { return null; }
// Binary operators
public static C operator >> (C a, int shift) { return null; }
public static C operator << (C a, int shift) { return null; }
public static C operator ^ (C a, C b) { return null; }
public static C operator | (C a, C b) { return null; }
public static C operator & (C a, C b) { return null; }
public static C operator % (C a, C b) { return null; }
public static C operator / (C a, C b) { return null; }
public static C operator * (C a, C b) { return null; }
public static C operator - (C a, C b) { return null; }
public static C operator + (C a, C b) { return null; }
// Comparison operators
public static bool operator >= (C a, C b) { return true; }
public static bool operator <= (C a, C b) { return true; }
public static bool operator > (C a, C b) { return true; }
public static bool operator < (C a, C b) { return true; }
public static bool operator != (C a, C b) { return true; }
public static bool operator == (C a, C b) { return true; }
}
}";
var initial = "namespace [|N|] { }";
var expected = @"namespace N
{
public class C
{
public static C operator +(C other);
public static C operator +(C a, C b);
public static C operator -(C other);
public static C operator -(C a, C b);
public static C operator !(C other);
public static C operator ~(C other);
public static C operator ++(C other);
public static C operator --(C other);
public static C operator *(C a, C b);
public static C operator /(C a, C b);
public static C operator %(C a, C b);
public static C operator &(C a, C b);
public static C operator |(C a, C b);
public static C operator ^(C a, C b);
public static C operator <<(C a, int shift);
public static C operator >>(C a, int shift);
public static bool operator ==(C a, C b);
public static bool operator !=(C a, C b);
public static bool operator <(C a, C b);
public static bool operator >(C a, C b);
public static bool operator <=(C a, C b);
public static bool operator >=(C a, C b);
public static bool operator true(C other);
public static bool operator false(C other);
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.CSharp,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
}
[WorkItem(665008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665008")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestExtensionMethods()
{
var generationSource = @"
public static class [|C|]
{
public static void ExtMethod1(this string s, int y, string z) {}
}";
var initial = "public static class [|C|] {}";
var expected = @"public static class C
{
public static void ExtMethod1(this string s, int y, string z);
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(530829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestVBPropertiesWithParams()
{
var generationSource = @"
Namespace N
Public Class [|C|]
Public Overridable Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class
End Namespace
";
var initial = "namespace [|N|] {}";
var expected = @"namespace N
{
public class C
{
public virtual string get_IndexProp(int p1);
public virtual void set_IndexProp(int p1, string value);
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(812738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812738")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestRefParamsWithDefaultValue()
{
var generationSource = @"
Public Class [|C|]
Public Sub Goo(x As Integer, Optional ByRef y As Integer = 10, Optional ByRef z As Object = Nothing)
End Sub
End Class";
var initial = "public class [|C|] {}";
var expected = @"public class C
{
public void Goo(int x, ref int y, ref object z);
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
namespace N
{
public class [|C|]<T, U> where T : struct where U : class
{
public void Goo<Q, R>() where Q : new() where R : IComparable { }
public delegate void D<T, U>(T t, U u) where T : struct where U : class;
}
}
";
var initial = "namespace [|N|] {}";
var expected = @"namespace N
{
public class C<T, U>
where T : struct
where U : class
{
public void Goo<Q, R>()
where Q : new()
where R : IComparable;
public delegate void D<T, U>(T t, U u)
where T : struct
where U : class;
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class VisualBasic
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "Namespace [|N1|]\n End Namespace";
var expected = @"Namespace N1
Namespace N2
End Namespace
End Namespace";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Private Shared F As String
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer()
End Class";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[WorkItem(530785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithXmlComment()
{
var input = @"
Public Class [|C|]
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
var expected = @"
Public Class C
Public Sub New()
End Sub
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Class";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "Class [|C|]\n End Class";
var expected = @"Imports System.Text
Class C
Public Sub New(s As StringBuilder)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(StringBuilder), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Shared Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class";
var expected = @"Class C
Public Sub New()
Me.New(42)
End Sub
Public Sub New(i As Integer)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544476")]
public async Task AddClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddNotInheritableClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public NotInheritable Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
modifiers: new DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddMustInheritClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend MustInherit Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Internal,
modifiers: new DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isSealed: true),
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Interface I
End Interface
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544528")]
public async Task AddEnum()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", null)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1 = 1
F2 = 2
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMember()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2 = 2
F3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMemberWithValue()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2
F3 = 3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3", hasConstantValue: true, constantValue: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544529")]
public async Task AddDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
modifiers: new DeclarationModifiers(isSealed: true),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Event E As Action
End Class";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessorAndImplementsClause()
{
var input = "Class [|C|] \n End Class";
var expected = @"Class C
Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged
AddHandler(value As ComponentModel.PropertyChangedEventHandler)
End AddHandler
RemoveHandler(value As ComponentModel.PropertyChangedEventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs)
End RaiseEvent
End Event
End Class";
static ImmutableArray<IEventSymbol> GetExplicitInterfaceEvent(SemanticModel semanticModel)
{
var parameterSymbols = SpecializedCollections.EmptyList<AttributeData>();
return ImmutableArray.Create<IEventSymbol>(
new CodeGenerationEventSymbol(
GetTypeSymbol(typeof(System.ComponentModel.INotifyPropertyChanged))(semanticModel),
attributes: default,
Accessibility.Public,
modifiers: default,
GetTypeSymbol(typeof(System.ComponentModel.PropertyChangedEventHandler))(semanticModel),
explicitInterfaceImplementations: default,
nameof(System.ComponentModel.INotifyPropertyChanged.PropertyChanged), null, null, null));
}
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
getExplicitInterfaceImplementations: GetExplicitInterfaceEvent,
type: typeof(System.ComponentModel.PropertyChangedEventHandler),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAddAccessor()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
Console.WriteLine(0)
End AddHandler
RemoveHandler(value As Action)
Console.WriteLine(1)
End RemoveHandler
RaiseEvent()
Console.WriteLine(2)
End RaiseEvent
End Event
End Class";
var addStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(0)"));
var removeStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(1)"));
var raiseStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(2)"));
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, addStatements),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, removeStatements),
raiseMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, raiseStatements),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Friend Sub [Sub]()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
name: "Sub",
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddSharedMethodToStructure()
{
var input = "Structure [|S|]\n End Structure";
var expected = @"Structure S
Public Shared Function M() As Integer
Return 0
End Function
End Structure";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNotOverridableOverridesMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public NotOverridable Overrides Function GetHashCode() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMustOverrideMethod()
{
var input = "MustInherit Class [|C|]\n End Class";
var expected = "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isAbstract: true),
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Function M(Of T)() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "Return new T().GetHashCode()");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Overridable Function M() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddShadowsMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shadows Function ToString() As String
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "ToString",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isNew: true),
returnType: typeof(string),
statements: "Return String.Empty");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class";
var expected = @"Interface I
Sub M(i As Integer)
End Interface
Class C
Implements I
Public Sub M(i As Integer) Implements I.M
End Sub
End Class";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator IsTrue(other As C) As Boolean
$$
End Operator
Public Shared Operator IsFalse(other As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return False");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(other As C) As Object
$$
End Operator
Public Shared Operator -(other As C) As Object
$$
End Operator
Public Shared Operator Not(other As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(a As C, b As C) As Object
$$
End Operator
Public Shared Operator -(a As C, b As C) As Object
$$
End Operator
Public Shared Operator *(a As C, b As C) As Object
$$
End Operator
Public Shared Operator /(a As C, b As C) As Object
$$
End Operator
Public Shared Operator \(a As C, b As C) As Object
$$
End Operator
Public Shared Operator ^(a As C, b As C) As Object
$$
End Operator
Public Shared Operator &(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Like(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Mod(a As C, b As C) As Object
$$
End Operator
Public Shared Operator And(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Or(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Xor(a As C, b As C) As Object
$$
End Operator
Public Shared Operator <<(a As C, b As C) As Object
$$
End Operator
Public Shared Operator >>(a As C, b As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.IntegerDivision,
CodeGenerationOperatorKind.Exponent,
CodeGenerationOperatorKind.Concatenate,
CodeGenerationOperatorKind.Like,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator =(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <>(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >=(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <=(a As C, b As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.GreaterThanOrEqual,
CodeGenerationOperatorKind.LessThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "Class [|C|]\n End Class";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Increment,
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Narrowing Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Widening Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToSub()
{
var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M
Console.WriteLine(1)
$$ End Sub
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2)");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToOperator()
{
var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(arg As C) As C
Return arg
$$ End Operator
End Class";
await TestAddStatementsAsync(input, expected, "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToPropertySetter()
{
var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class";
var expected = @"Imports System
Class C
WriteOnly Property P As String
Set
$$ End Set
End Property
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(\"Setting the value\"");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M(numAs Integer, OptionaltextAs String = ""Hello!"",OptionalfloatingAs Single = 0.5)
End Sub
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F)));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyBlock()
{
var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyStatement()
{
var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyGetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertySetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToOperator()
{
var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(a As C,bAs C) As C
Return a
End Operator
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter("C", "b")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAutoProperty()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyWithoutAccessorBodies()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
getStatements: "Return 0",
setStatements: "Me.P = Value",
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Default Public ReadOnly Property Item(i As Integer) As String
Get
$$
End Get
End Property
End Class";
await TestAddPropertyAsync(input, expected,
name: "Item",
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "Return String.Empty",
isIndexer: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "Class [|C|]\n End Class";
var expected = @"<Serializable>
Class C
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"
<Serializable>
Class [|C|]
End Class";
var expected = @"
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class";
var expected = @"Class C
<Serializable>
Public Sub M()
End Sub
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = @"
Class C
<Serializable>
Public Sub [|M()|]
End Sub
End Class";
var expected = @"
Class C
Public Sub M()
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "Class C\n [|Public F As Integer|]\n End Class";
var expected = @"Class C
<Serializable>
Public F As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = @"
Class C
<Serializable>
Public [|F|] As Integer
End Class";
var expected = @"
Class C
Public F As Integer
End Class";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "Class C \n Public Property [|P|] As Integer \n End Class";
var expected = @"Class C
<Serializable>
Public Property P As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = @"
Class C
<Serializable>
Public Property [|P|] As Integer
End Class";
var expected = @"
Class C
Public Property P As Integer
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class";
var expected = @"Class C
Public ReadOnly Property P As Integer
<Serializable>
Get
Return 10
End Get
End Property
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = @"
Class C
Public Property P As Integer
<Serializable>
[|Get|]
Return 10
End Get
End Class";
var expected = @"
Class C
Public Property P As Integer
Get
Return 10
End Get
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module";
var expected = @"Module M
<Serializable>
Enum C
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = @"
Module M
<Serializable>
Enum [|C|]
One
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module";
var expected = @"Module M
Enum C
<Serializable>
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = @"
Module M
Enum C
<Serializable>
[|One|]
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToModule()
{
var input = "Module [|M|] \n End Module";
var expected = @"<Serializable>
Module M
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromModule()
{
var input = @"
<Serializable>
Module [|M|]
End Module";
var expected = @"
Module M
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class";
var expected = @"Class C
<Serializable>
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = @"
Module M
Class C
<Serializable>
Public Shared Operator [|+|](x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
var expected = @"
Module M
Class C
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "Module M \n Delegate Sub [|D()|]\n End Module";
var expected = "Module M\n <Serializable>\n Delegate Sub D()\nEnd Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = @"
Module M
<Serializable>
Delegate Sub [|D()|]
End Module";
var expected = @"
Module M
Delegate Sub D()
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class";
var expected = "Class C \n Public Sub M(<Serializable> x As Integer) \n End Sub \n End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = @"
Class C
Public Sub M(<Serializable> [|x As Integer|])
End Sub
End Class";
var expected = @"
Class C
Public Sub M(x As Integer)
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable>\nClass C\nEnd Class\nClass D\nEnd Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"' Comment 1
<System.Serializable> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"' Comment 1
<System.Serializable>
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attribute lists.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"Friend Partial NotInheritable Class C ' Comment 1
' Comment 2
End Class";
var eol = VB.SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic));
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"' Comment 0
Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"' Comment 0
Protected Friend Shared Class C ' Comment 1
' Comment 2
End Class";
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, accessibility: Accessibility.ProtectedOrFriend);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
Public Shared Class C
' Comment 1
Public Shared Function [|F|]() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 1
Public Shared Function F() As Integer
Return 0
End Function
End Class";
await TestUpdateDeclarationAsync<MethodStatementSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
Public Shared Class [|C|]
' Comment 0
Public Shared {|RetainedMember:f|} As Integer
' Comment 1
Public Shared Function F() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 0
Public Shared f As Integer
Public Shared f2 As Integer
End Class";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassBlockSyntax>(input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortModules()
{
var generationSource = "Public Class [|C|] \n End Class";
var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
Module M
End Module
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
Namespace N
Public Class [|C|]
' Unary operators
Public Shared Operator IsFalse(other As C) As Boolean
Return False
End Operator
Public Shared Operator IsTrue(other As C) As Boolean
Return True
End Operator
Public Shared Operator Not(other As C) As C
Return Nothing
End Operator
Public Shared Operator -(other As C) As C
Return Nothing
End Operator
Public Shared Operator + (other As C) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(c As C) As Integer
Return 0
End Operator
' Binary operators
Public Shared Operator >= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator > (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator < (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <> (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator = (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator >> (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator << (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator Xor(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Or(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator And(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Mod(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Like (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator & (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator ^ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator \ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator / (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator *(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator -(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator + (a As C, b As C) As C
Return Nothing
End Operator
End Class
End Namespace";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C
Public Shared Operator +(other As C) As C
Public Shared Operator +(a As C, b As C) As C
Public Shared Operator -(other As C) As C
Public Shared Operator -(a As C, b As C) As C
Public Shared Operator *(a As C, b As C) As C
Public Shared Operator /(a As C, b As C) As C
Public Shared Operator \(a As C, b As C) As C
Public Shared Operator ^(a As C, b As C) As C
Public Shared Operator &(a As C, b As C) As C
Public Shared Operator Not(other As C) As C
Public Shared Operator Like(a As C, b As C) As C
Public Shared Operator Mod(a As C, b As C) As C
Public Shared Operator And(a As C, b As C) As C
Public Shared Operator Or(a As C, b As C) As C
Public Shared Operator Xor(a As C, b As C) As C
Public Shared Operator <<(a As C, shift As Integer) As C
Public Shared Operator >>(a As C, shift As Integer) As C
Public Shared Operator =(a As C, b As C) As Boolean
Public Shared Operator <>(a As C, b As C) As Boolean
Public Shared Operator >(a As C, b As C) As Boolean
Public Shared Operator <(a As C, b As C) As Boolean
Public Shared Operator >=(a As C, b As C) As Boolean
Public Shared Operator <=(a As C, b As C) As Boolean
Public Shared Operator IsTrue(other As C) As Boolean
Public Shared Operator IsFalse(other As C) As Boolean
Public Shared Narrowing Operator CType(c As C) As Integer
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.VisualBasic,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
Namespace N
Public Class [|C|](Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
End Sub
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace
";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C(Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class VisualBasic
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "Namespace [|N1|]\n End Namespace";
var expected = @"Namespace N1
Namespace N2
End Namespace
End Namespace";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Private Shared F As String
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer()
End Class";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[WorkItem(530785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithXmlComment()
{
var input = @"
Public Class [|C|]
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
var expected = @"
Public Class C
Public Sub New()
End Sub
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Class";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "Class [|C|]\n End Class";
var expected = @"Imports System.Text
Class C
Public Sub New(s As StringBuilder)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(StringBuilder), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Shared Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class";
var expected = @"Class C
Public Sub New()
Me.New(42)
End Sub
Public Sub New(i As Integer)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544476")]
public async Task AddClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddNotInheritableClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public NotInheritable Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
modifiers: new DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddMustInheritClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend MustInherit Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Internal,
modifiers: new DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isSealed: true),
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Interface I
End Interface
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544528")]
public async Task AddEnum()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", null)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1 = 1
F2 = 2
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMember()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2 = 2
F3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMemberWithValue()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2
F3 = 3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3", hasConstantValue: true, constantValue: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544529")]
public async Task AddDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
modifiers: new DeclarationModifiers(isSealed: true),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Event E As Action
End Class";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddCustomEventToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessorAndImplementsClause()
{
var input = "Class [|C|] \n End Class";
var expected = @"Class C
Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged
AddHandler(value As ComponentModel.PropertyChangedEventHandler)
End AddHandler
RemoveHandler(value As ComponentModel.PropertyChangedEventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs)
End RaiseEvent
End Event
End Class";
static ImmutableArray<IEventSymbol> GetExplicitInterfaceEvent(SemanticModel semanticModel)
{
var parameterSymbols = SpecializedCollections.EmptyList<AttributeData>();
return ImmutableArray.Create<IEventSymbol>(
new CodeGenerationEventSymbol(
GetTypeSymbol(typeof(System.ComponentModel.INotifyPropertyChanged))(semanticModel),
attributes: default,
Accessibility.Public,
modifiers: default,
GetTypeSymbol(typeof(System.ComponentModel.PropertyChangedEventHandler))(semanticModel),
explicitInterfaceImplementations: default,
nameof(System.ComponentModel.INotifyPropertyChanged.PropertyChanged), null, null, null));
}
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
getExplicitInterfaceImplementations: GetExplicitInterfaceEvent,
type: typeof(System.ComponentModel.PropertyChangedEventHandler),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAddAccessor()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
Console.WriteLine(0)
End AddHandler
RemoveHandler(value As Action)
Console.WriteLine(1)
End RemoveHandler
RaiseEvent()
Console.WriteLine(2)
End RaiseEvent
End Event
End Class";
var addStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(0)"));
var removeStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(1)"));
var raiseStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(2)"));
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, addStatements),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, removeStatements),
raiseMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, raiseStatements),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Function FInt() As Integer
Return 0
End Function
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Function FInt() As Integer
Return 0
End Function
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Friend Sub [Sub]()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
name: "Sub",
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddSharedMethodToStructure()
{
var input = "Structure [|S|]\n End Structure";
var expected = @"Structure S
Public Shared Function M() As Integer
Return 0
End Function
End Structure";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNotOverridableOverridesMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public NotOverridable Overrides Function GetHashCode() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMustOverrideMethod()
{
var input = "MustInherit Class [|C|]\n End Class";
var expected = "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isAbstract: true),
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Function M(Of T)() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "Return new T().GetHashCode()");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Overridable Function M() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddShadowsMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shadows Function ToString() As String
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "ToString",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isNew: true),
returnType: typeof(string),
statements: "Return String.Empty");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class";
var expected = @"Interface I
Sub M(i As Integer)
End Interface
Class C
Implements I
Public Sub M(i As Integer) Implements I.M
End Sub
End Class";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator IsTrue(other As C) As Boolean
$$
End Operator
Public Shared Operator IsFalse(other As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return False");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(other As C) As Object
$$
End Operator
Public Shared Operator -(other As C) As Object
$$
End Operator
Public Shared Operator Not(other As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(a As C, b As C) As Object
$$
End Operator
Public Shared Operator -(a As C, b As C) As Object
$$
End Operator
Public Shared Operator *(a As C, b As C) As Object
$$
End Operator
Public Shared Operator /(a As C, b As C) As Object
$$
End Operator
Public Shared Operator \(a As C, b As C) As Object
$$
End Operator
Public Shared Operator ^(a As C, b As C) As Object
$$
End Operator
Public Shared Operator &(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Like(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Mod(a As C, b As C) As Object
$$
End Operator
Public Shared Operator And(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Or(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Xor(a As C, b As C) As Object
$$
End Operator
Public Shared Operator <<(a As C, b As C) As Object
$$
End Operator
Public Shared Operator >>(a As C, b As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.IntegerDivision,
CodeGenerationOperatorKind.Exponent,
CodeGenerationOperatorKind.Concatenate,
CodeGenerationOperatorKind.Like,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator =(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <>(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >=(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <=(a As C, b As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.GreaterThanOrEqual,
CodeGenerationOperatorKind.LessThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "Class [|C|]\n End Class";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Increment,
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Narrowing Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Widening Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToSub()
{
var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M
Console.WriteLine(1)
$$ End Sub
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2)");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToOperator()
{
var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(arg As C) As C
Return arg
$$ End Operator
End Class";
await TestAddStatementsAsync(input, expected, "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToPropertySetter()
{
var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class";
var expected = @"Imports System
Class C
WriteOnly Property P As String
Set
$$ End Set
End Property
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(\"Setting the value\"");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M(numAs Integer, OptionaltextAs String = ""Hello!"",OptionalfloatingAs Single = 0.5)
End Sub
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F)));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyBlock()
{
var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyStatement()
{
var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyGetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertySetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToOperator()
{
var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(a As C,bAs C) As C
Return a
End Operator
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter("C", "b")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAutoProperty()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyWithoutAccessorBodies()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
getStatements: "Return 0",
setStatements: "Me.P = Value",
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Default Public ReadOnly Property Item(i As Integer) As String
Get
$$
End Get
End Property
End Class";
await TestAddPropertyAsync(input, expected,
name: "Item",
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "Return String.Empty",
isIndexer: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "Class [|C|]\n End Class";
var expected = @"<Serializable>
Class C
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"
<Serializable>
Class [|C|]
End Class";
var expected = @"
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class";
var expected = @"Class C
<Serializable>
Public Sub M()
End Sub
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = @"
Class C
<Serializable>
Public Sub [|M()|]
End Sub
End Class";
var expected = @"
Class C
Public Sub M()
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "Class C\n [|Public F As Integer|]\n End Class";
var expected = @"Class C
<Serializable>
Public F As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = @"
Class C
<Serializable>
Public [|F|] As Integer
End Class";
var expected = @"
Class C
Public F As Integer
End Class";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "Class C \n Public Property [|P|] As Integer \n End Class";
var expected = @"Class C
<Serializable>
Public Property P As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = @"
Class C
<Serializable>
Public Property [|P|] As Integer
End Class";
var expected = @"
Class C
Public Property P As Integer
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class";
var expected = @"Class C
Public ReadOnly Property P As Integer
<Serializable>
Get
Return 10
End Get
End Property
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = @"
Class C
Public Property P As Integer
<Serializable>
[|Get|]
Return 10
End Get
End Class";
var expected = @"
Class C
Public Property P As Integer
Get
Return 10
End Get
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module";
var expected = @"Module M
<Serializable>
Enum C
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = @"
Module M
<Serializable>
Enum [|C|]
One
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module";
var expected = @"Module M
Enum C
<Serializable>
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = @"
Module M
Enum C
<Serializable>
[|One|]
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToModule()
{
var input = "Module [|M|] \n End Module";
var expected = @"<Serializable>
Module M
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromModule()
{
var input = @"
<Serializable>
Module [|M|]
End Module";
var expected = @"
Module M
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class";
var expected = @"Class C
<Serializable>
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = @"
Module M
Class C
<Serializable>
Public Shared Operator [|+|](x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
var expected = @"
Module M
Class C
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "Module M \n Delegate Sub [|D()|]\n End Module";
var expected = "Module M\n <Serializable>\n Delegate Sub D()\nEnd Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = @"
Module M
<Serializable>
Delegate Sub [|D()|]
End Module";
var expected = @"
Module M
Delegate Sub D()
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class";
var expected = "Class C \n Public Sub M(<Serializable> x As Integer) \n End Sub \n End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = @"
Class C
Public Sub M(<Serializable> [|x As Integer|])
End Sub
End Class";
var expected = @"
Class C
Public Sub M(x As Integer)
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable>\nClass C\nEnd Class\nClass D\nEnd Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"' Comment 1
<System.Serializable> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"' Comment 1
<System.Serializable>
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attribute lists.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"Friend Partial NotInheritable Class C ' Comment 1
' Comment 2
End Class";
var eol = VB.SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic));
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"' Comment 0
Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"' Comment 0
Protected Friend Shared Class C ' Comment 1
' Comment 2
End Class";
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, accessibility: Accessibility.ProtectedOrFriend);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
Public Shared Class C
' Comment 1
Public Shared Function [|F|]() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 1
Public Shared Function F() As Integer
Return 0
End Function
End Class";
await TestUpdateDeclarationAsync<MethodStatementSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
Public Shared Class [|C|]
' Comment 0
Public Shared {|RetainedMember:f|} As Integer
' Comment 1
Public Shared Function F() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 0
Public Shared f As Integer
Public Shared f2 As Integer
End Class";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassBlockSyntax>(input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortModules()
{
var generationSource = "Public Class [|C|] \n End Class";
var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
Module M
End Module
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
Namespace N
Public Class [|C|]
' Unary operators
Public Shared Operator IsFalse(other As C) As Boolean
Return False
End Operator
Public Shared Operator IsTrue(other As C) As Boolean
Return True
End Operator
Public Shared Operator Not(other As C) As C
Return Nothing
End Operator
Public Shared Operator -(other As C) As C
Return Nothing
End Operator
Public Shared Operator + (other As C) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(c As C) As Integer
Return 0
End Operator
' Binary operators
Public Shared Operator >= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator > (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator < (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <> (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator = (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator >> (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator << (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator Xor(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Or(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator And(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Mod(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Like (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator & (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator ^ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator \ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator / (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator *(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator -(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator + (a As C, b As C) As C
Return Nothing
End Operator
End Class
End Namespace";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C
Public Shared Operator +(other As C) As C
Public Shared Operator +(a As C, b As C) As C
Public Shared Operator -(other As C) As C
Public Shared Operator -(a As C, b As C) As C
Public Shared Operator *(a As C, b As C) As C
Public Shared Operator /(a As C, b As C) As C
Public Shared Operator \(a As C, b As C) As C
Public Shared Operator ^(a As C, b As C) As C
Public Shared Operator &(a As C, b As C) As C
Public Shared Operator Not(other As C) As C
Public Shared Operator Like(a As C, b As C) As C
Public Shared Operator Mod(a As C, b As C) As C
Public Shared Operator And(a As C, b As C) As C
Public Shared Operator Or(a As C, b As C) As C
Public Shared Operator Xor(a As C, b As C) As C
Public Shared Operator <<(a As C, shift As Integer) As C
Public Shared Operator >>(a As C, shift As Integer) As C
Public Shared Operator =(a As C, b As C) As Boolean
Public Shared Operator <>(a As C, b As C) As Boolean
Public Shared Operator >(a As C, b As C) As Boolean
Public Shared Operator <(a As C, b As C) As Boolean
Public Shared Operator >=(a As C, b As C) As Boolean
Public Shared Operator <=(a As C, b As C) As Boolean
Public Shared Operator IsTrue(other As C) As Boolean
Public Shared Operator IsFalse(other As C) As Boolean
Public Shared Narrowing Operator CType(c As C) As Integer
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.VisualBasic,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
Namespace N
Public Class [|C|](Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
End Sub
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace
";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C(Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
}
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxNodeExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SyntaxNodeExtensions
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsKind(kind)
End Function
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
IsKind(node.Parent, kind1, kind2)
End Function
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
IsKind(node.Parent, kind1, kind2, kind3)
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2 OrElse
node.Kind = kind3
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind, kind4 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2 OrElse
node.Kind = kind3 OrElse
node.Kind = kind4
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, ParamArray kinds As SyntaxKind()) As Boolean
If node Is Nothing Then
Return False
End If
Return kinds.Contains(node.Kind())
End Function
<Extension()>
Public Function IsInConstantContext(expression As SyntaxNode) As Boolean
If expression.GetAncestor(Of ParameterSyntax)() IsNot Nothing Then
Return True
End If
' TODO(cyrusn): Add more cases
Return False
End Function
<Extension()>
Public Function IsInStaticContext(node As SyntaxNode) As Boolean
Dim containingType = node.GetAncestorOrThis(Of TypeBlockSyntax)()
If containingType.IsKind(SyntaxKind.ModuleBlock) Then
Return True
End If
Return node.GetAncestorsOrThis(Of StatementSyntax)().
SelectMany(Function(s) s.GetModifiers()).
Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
End Function
<Extension()>
Public Function IsStatementContainerNode(node As SyntaxNode) As Boolean
If node.IsExecutableBlock() Then
Return True
End If
Dim singleLineLambdaExpression = TryCast(node, SingleLineLambdaExpressionSyntax)
If singleLineLambdaExpression IsNot Nothing AndAlso TypeOf singleLineLambdaExpression.Body Is ExecutableStatementSyntax Then
Return True
End If
Return False
End Function
<Extension()>
Public Function GetStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
Contract.ThrowIfNull(node)
Contract.ThrowIfFalse(node.IsStatementContainerNode())
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Return methodBlock.Statements
End If
Dim whileBlock = TryCast(node, WhileBlockSyntax)
If whileBlock IsNot Nothing Then
Return whileBlock.Statements
End If
Dim usingBlock = TryCast(node, UsingBlockSyntax)
If usingBlock IsNot Nothing Then
Return usingBlock.Statements
End If
Dim syncLockBlock = TryCast(node, SyncLockBlockSyntax)
If syncLockBlock IsNot Nothing Then
Return syncLockBlock.Statements
End If
Dim withBlock = TryCast(node, WithBlockSyntax)
If withBlock IsNot Nothing Then
Return withBlock.Statements
End If
Dim singleLineIfStatement = TryCast(node, SingleLineIfStatementSyntax)
If singleLineIfStatement IsNot Nothing Then
Return singleLineIfStatement.Statements
End If
Dim singleLineElseClause = TryCast(node, SingleLineElseClauseSyntax)
If singleLineElseClause IsNot Nothing Then
Return singleLineElseClause.Statements
End If
Dim ifBlock = TryCast(node, MultiLineIfBlockSyntax)
If ifBlock IsNot Nothing Then
Return ifBlock.Statements
End If
Dim elseIfBlock = TryCast(node, ElseIfBlockSyntax)
If elseIfBlock IsNot Nothing Then
Return elseIfBlock.Statements
End If
Dim elseBlock = TryCast(node, ElseBlockSyntax)
If elseBlock IsNot Nothing Then
Return elseBlock.Statements
End If
Dim tryBlock = TryCast(node, TryBlockSyntax)
If tryBlock IsNot Nothing Then
Return tryBlock.Statements
End If
Dim catchBlock = TryCast(node, CatchBlockSyntax)
If catchBlock IsNot Nothing Then
Return catchBlock.Statements
End If
Dim finallyBlock = TryCast(node, FinallyBlockSyntax)
If finallyBlock IsNot Nothing Then
Return finallyBlock.Statements
End If
Dim caseBlock = TryCast(node, CaseBlockSyntax)
If caseBlock IsNot Nothing Then
Return caseBlock.Statements
End If
Dim doLoopBlock = TryCast(node, DoLoopBlockSyntax)
If doLoopBlock IsNot Nothing Then
Return doLoopBlock.Statements
End If
Dim forBlock = TryCast(node, ForOrForEachBlockSyntax)
If forBlock IsNot Nothing Then
Return forBlock.Statements
End If
Dim singleLineLambdaExpression = TryCast(node, SingleLineLambdaExpressionSyntax)
If singleLineLambdaExpression IsNot Nothing Then
Return If(TypeOf singleLineLambdaExpression.Body Is StatementSyntax,
SyntaxFactory.SingletonList(DirectCast(singleLineLambdaExpression.Body, StatementSyntax)),
Nothing)
End If
Dim multiLineLambdaExpression = TryCast(node, MultiLineLambdaExpressionSyntax)
If multiLineLambdaExpression IsNot Nothing Then
Return multiLineLambdaExpression.Statements
End If
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
<Extension()>
Friend Function IsAsyncSupportedFunctionSyntax(node As SyntaxNode) As Boolean
Select Case node?.Kind()
Case _
SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return True
End Select
Return False
End Function
<Extension()>
Friend Function IsMultiLineLambda(node As SyntaxNode) As Boolean
Return SyntaxFacts.IsMultiLineLambdaExpression(node.Kind())
End Function
<Extension()>
Friend Function GetTypeCharacterString(type As TypeCharacter) As String
Select Case type
Case TypeCharacter.Integer
Return "%"
Case TypeCharacter.Long
Return "&"
Case TypeCharacter.Decimal
Return "@"
Case TypeCharacter.Single
Return "!"
Case TypeCharacter.Double
Return "#"
Case TypeCharacter.String
Return "$"
Case Else
Throw New ArgumentException("Unexpected TypeCharacter.", NameOf(type))
End Select
End Function
<Extension()>
Public Function SpansPreprocessorDirective(Of TSyntaxNode As SyntaxNode)(list As IEnumerable(Of TSyntaxNode)) As Boolean
Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(list)
End Function
<Extension()>
Public Function ConvertToSingleLine(Of TNode As SyntaxNode)(node As TNode, Optional useElasticTrivia As Boolean = False) As TNode
If node Is Nothing Then
Return node
End If
Dim rewriter = New SingleLineRewriter(useElasticTrivia)
Return DirectCast(rewriter.Visit(node), TNode)
End Function
''' <summary>
''' Breaks up the list of provided nodes, based on how they are
''' interspersed with pp directives, into groups. Within these groups
''' nodes can be moved around safely, without breaking any pp
''' constructs.
''' </summary>
<Extension()>
Public Function SplitNodesOnPreprocessorBoundaries(Of TSyntaxNode As SyntaxNode)(
nodes As IEnumerable(Of TSyntaxNode),
cancellationToken As CancellationToken) As IList(Of IList(Of TSyntaxNode))
Dim result = New List(Of IList(Of TSyntaxNode))()
Dim currentGroup = New List(Of TSyntaxNode)()
For Each node In nodes
Dim hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken)
Dim hasLeadingDirective = node.GetLeadingTrivia().Any(Function(t) SyntaxFacts.IsPreprocessorDirective(t.Kind))
If hasUnmatchedInteriorDirective Then
' we have a #if/#endif/#region/#endregion/#else/#elif in
' this node that belongs to a span of pp directives that
' is not entirely contained within the node. i.e.:
'
' void Goo() {
' #if ...
' }
'
' This node cannot be moved at all. It is in a group that
' only contains itself (and thus can never be moved).
' add whatever group we've built up to now. And reset the
' next group to empty.
result.Add(currentGroup)
currentGroup = New List(Of TSyntaxNode)()
result.Add(New List(Of TSyntaxNode) From {node})
ElseIf hasLeadingDirective Then
' We have a PP directive before us. i.e.:
'
' #if ...
' void Goo() {
'
' That means we start a new group that is contained between
' the above directive and the following directive.
' add whatever group we've built up to now. And reset the
' next group to empty.
result.Add(currentGroup)
currentGroup = New List(Of TSyntaxNode)()
currentGroup.Add(node)
Else
' simple case. just add ourselves to the current group
currentGroup.Add(node)
End If
Next
' add the remainder of the final group.
result.Add(currentGroup)
' Now, filter out any empty groups.
result = result.Where(Function(group) Not group.IsEmpty()).ToList()
Return result
End Function
''' <summary>
''' Returns true if the passed in node contains an interleaved pp
''' directive.
'''
''' i.e. The following returns false:
'''
''' void Goo() {
''' #if true
''' #endif
''' }
'''
''' #if true
''' void Goo() {
''' }
''' #endif
'''
''' but these return true:
'''
''' #if true
''' void Goo() {
''' #endif
''' }
'''
''' void Goo() {
''' #if true
''' }
''' #endif
'''
''' #if true
''' void Goo() {
''' #else
''' }
''' #endif
'''
''' i.e. the method returns true if it contains a PP directive that
''' belongs to a grouping constructs (like #if/#endif or
''' #region/#endregion), but the grouping construct isn't entirely c
''' contained within the span of the node.
''' </summary>
<Extension()>
Public Function ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Return VisualBasicSyntaxFacts.Instance.ContainsInterleavedDirective(node, cancellationToken)
End Function
<Extension>
Public Function ContainsInterleavedDirective(
token As SyntaxToken,
textSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
Return ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) OrElse
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken)
End Function
Private Function ContainsInterleavedDirective(
textSpan As TextSpan,
list As SyntaxTriviaList,
cancellationToken As CancellationToken) As Boolean
For Each trivia In list
If textSpan.Contains(trivia.Span) Then
If ContainsInterleavedDirective(textSpan, trivia, cancellationToken) Then
Return True
End If
End If
Next trivia
Return False
End Function
Private Function ContainsInterleavedDirective(
textSpan As TextSpan,
trivia As SyntaxTrivia,
cancellationToken As CancellationToken) As Boolean
If trivia.HasStructure AndAlso TypeOf trivia.GetStructure() Is DirectiveTriviaSyntax Then
Dim parentSpan = trivia.GetStructure().Span
Dim directiveSyntax = DirectCast(trivia.GetStructure(), DirectiveTriviaSyntax)
If directiveSyntax.IsKind(SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.IfDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia) Then
Dim match = directiveSyntax.GetMatchingStartOrEndDirective(cancellationToken)
If match IsNot Nothing Then
Dim matchSpan = match.Span
If Not textSpan.Contains(matchSpan.Start) Then
' The match for this pp directive is outside
' this node.
Return True
End If
End If
ElseIf directiveSyntax.IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia) Then
Dim directives = directiveSyntax.GetMatchingConditionalDirectives(cancellationToken)
If directives IsNot Nothing AndAlso directives.Count > 0 Then
If Not textSpan.Contains(directives(0).SpanStart) OrElse
Not textSpan.Contains(directives(directives.Count - 1).SpanStart) Then
' This else/elif belongs to a pp span that isn't
' entirely within this node.
Return True
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function GetLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As ImmutableArray(Of SyntaxTrivia)
Return VisualBasicSyntaxFacts.Instance.GetLeadingBlankLines(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode, ByRef strippedTrivia As ImmutableArray(Of SyntaxTrivia)) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, strippedTrivia)
End Function
<Extension()>
Public Function GetLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As ImmutableArray(Of SyntaxTrivia)
Return VisualBasicSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode, ByRef strippedTrivia As ImmutableArray(Of SyntaxTrivia)) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, strippedTrivia)
End Function
''' <summary>
''' Returns true if this is a block that can contain multiple executable statements. i.e.
''' this node is the VB equivalent of a BlockSyntax in C#.
''' </summary>
<Extension()>
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean
If node IsNot Nothing Then
If TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is DoLoopBlockSyntax OrElse
TypeOf node Is ForOrForEachBlockSyntax OrElse
TypeOf node Is MultiLineLambdaExpressionSyntax Then
Return True
End If
Select Case node.Kind
Case SyntaxKind.WhileBlock,
SyntaxKind.UsingBlock,
SyntaxKind.SyncLockBlock,
SyntaxKind.WithBlock,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.SingleLineElseClause,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineIfBlock,
SyntaxKind.ElseIfBlock,
SyntaxKind.ElseBlock,
SyntaxKind.TryBlock,
SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock,
SyntaxKind.CaseBlock,
SyntaxKind.CaseElseBlock
Return True
End Select
End If
Return False
End Function
<Extension()>
Public Function GetContainingExecutableBlocks(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return node.GetAncestorsOrThis(Of StatementSyntax).
Where(Function(s) s.Parent.IsExecutableBlock() AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).
Select(Function(s) s.Parent)
End Function
<Extension()>
Public Function GetContainingMultiLineExecutableBlocks(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return node.GetAncestorsOrThis(Of StatementSyntax).
Where(Function(s) s.Parent.IsMultiLineExecutableBlock AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).
Select(Function(s) s.Parent)
End Function
<Extension()>
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim blocks As IEnumerable(Of SyntaxNode) = Nothing
For Each node In nodes
blocks = If(blocks Is Nothing,
node.GetContainingExecutableBlocks(),
blocks.Intersect(node.GetContainingExecutableBlocks()))
Next
Return If(blocks Is Nothing, Nothing, blocks.FirstOrDefault())
End Function
<Extension()>
Public Function GetExecutableBlockStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
If node IsNot Nothing Then
If TypeOf node Is MethodBlockBaseSyntax Then
Return DirectCast(node, MethodBlockBaseSyntax).Statements
ElseIf TypeOf node Is DoLoopBlockSyntax Then
Return DirectCast(node, DoLoopBlockSyntax).Statements
ElseIf TypeOf node Is ForOrForEachBlockSyntax Then
Return DirectCast(node, ForOrForEachBlockSyntax).Statements
ElseIf TypeOf node Is MultiLineLambdaExpressionSyntax Then
Return DirectCast(node, MultiLineLambdaExpressionSyntax).Statements
End If
Select Case node.Kind
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).Statements
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).Statements
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).Statements
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).Statements
Case SyntaxKind.SingleLineIfStatement
Return DirectCast(node, SingleLineIfStatementSyntax).Statements
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).Statements
Case SyntaxKind.SingleLineSubLambdaExpression
Return SyntaxFactory.SingletonList(DirectCast(DirectCast(node, SingleLineLambdaExpressionSyntax).Body, StatementSyntax))
Case SyntaxKind.MultiLineIfBlock
Return DirectCast(node, MultiLineIfBlockSyntax).Statements
Case SyntaxKind.ElseIfBlock
Return DirectCast(node, ElseIfBlockSyntax).Statements
Case SyntaxKind.ElseBlock
Return DirectCast(node, ElseBlockSyntax).Statements
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).Statements
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).Statements
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).Statements
Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock
Return DirectCast(node, CaseBlockSyntax).Statements
End Select
End If
Return Nothing
End Function
''' <summary>
''' Returns child node or token that contains given position.
''' </summary>
''' <remarks>
''' This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
''' </remarks>
<Extension>
Friend Function ChildThatContainsPosition(self As SyntaxNode, position As Integer, ByRef childIndex As Integer) As SyntaxNodeOrToken
Dim childList = self.ChildNodesAndTokens()
Dim left As Integer = 0
Dim right As Integer = childList.Count - 1
While left <= right
Dim middle As Integer = left + (right - left) \ 2
Dim node As SyntaxNodeOrToken = childList(middle)
Dim span = node.FullSpan
If position < span.Start Then
right = middle - 1
ElseIf position >= span.End Then
left = middle + 1
Else
childIndex = middle
Return node
End If
End While
Debug.Assert(Not self.FullSpan.Contains(position), "Position is valid. How could we not find a child?")
Throw New ArgumentOutOfRangeException(NameOf(position))
End Function
<Extension()>
Public Function ReplaceStatements(node As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
Return node.TypeSwitch(
Function(x As MethodBlockSyntax) x.WithStatements(statements),
Function(x As ConstructorBlockSyntax) x.WithStatements(statements),
Function(x As OperatorBlockSyntax) x.WithStatements(statements),
Function(x As AccessorBlockSyntax) x.WithStatements(statements),
Function(x As DoLoopBlockSyntax) x.WithStatements(statements),
Function(x As ForBlockSyntax) x.WithStatements(statements),
Function(x As ForEachBlockSyntax) x.WithStatements(statements),
Function(x As MultiLineLambdaExpressionSyntax) x.WithStatements(statements),
Function(x As WhileBlockSyntax) x.WithStatements(statements),
Function(x As UsingBlockSyntax) x.WithStatements(statements),
Function(x As SyncLockBlockSyntax) x.WithStatements(statements),
Function(x As WithBlockSyntax) x.WithStatements(statements),
Function(x As SingleLineIfStatementSyntax) x.WithStatements(statements),
Function(x As SingleLineElseClauseSyntax) x.WithStatements(statements),
Function(x As SingleLineLambdaExpressionSyntax) ReplaceSingleLineLambdaExpressionStatements(x, statements, annotations),
Function(x As MultiLineIfBlockSyntax) x.WithStatements(statements),
Function(x As ElseIfBlockSyntax) x.WithStatements(statements),
Function(x As ElseBlockSyntax) x.WithStatements(statements),
Function(x As TryBlockSyntax) x.WithStatements(statements),
Function(x As CatchBlockSyntax) x.WithStatements(statements),
Function(x As FinallyBlockSyntax) x.WithStatements(statements),
Function(x As CaseBlockSyntax) x.WithStatements(statements))
End Function
<Extension()>
Public Function ReplaceSingleLineLambdaExpressionStatements(
node As SingleLineLambdaExpressionSyntax,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
Dim singleLineLambda = DirectCast(node, SingleLineLambdaExpressionSyntax)
If statements.Count = 1 Then
Return node.WithBody(statements.First())
Else
#If False Then
Dim statementsAndSeparators = statements.GetWithSeparators()
If statementsAndSeparators.LastOrDefault().IsNode Then
statements = Syntax.SeparatedList(Of StatementSyntax)(
statementsAndSeparators.Concat(Syntax.Token(SyntaxKind.StatementTerminatorToken)))
End If
#End If
Return SyntaxFactory.MultiLineSubLambdaExpression(
singleLineLambda.SubOrFunctionHeader,
statements,
SyntaxFactory.EndSubStatement()).WithAdditionalAnnotations(annotations)
End If
End If
' Can't be called on a single line lambda (as it can't have statements for children)
Throw New InvalidOperationException()
End Function
<Extension()>
Public Function ReplaceStatements(tree As SyntaxTree,
executableBlock As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
If executableBlock.IsSingleLineExecutableBlock() Then
Return ConvertSingleLineToMultiLineExecutableBlock(tree, executableBlock, statements, annotations)
End If
' TODO(cyrusn): Implement this.
Throw ExceptionUtilities.Unreachable
End Function
<Extension()>
Public Function IsSingleLineExecutableBlock(executableBlock As SyntaxNode) As Boolean
Select Case executableBlock.Kind
Case SyntaxKind.SingleLineElseClause,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.SingleLineSubLambdaExpression
Return executableBlock.GetExecutableBlockStatements().Count = 1
Case Else
Return False
End Select
End Function
<Extension()>
Public Function IsMultiLineExecutableBlock(node As SyntaxNode) As Boolean
Return node.IsExecutableBlock AndAlso Not node.IsSingleLineExecutableBlock
End Function
Private Sub UpdateStatements(executableBlock As SyntaxNode,
newStatements As SyntaxList(Of StatementSyntax),
annotations As SyntaxAnnotation(),
ByRef singleLineIf As SingleLineIfStatementSyntax,
ByRef multiLineIf As MultiLineIfBlockSyntax)
Dim ifStatements As SyntaxList(Of StatementSyntax)
Dim elseStatements As SyntaxList(Of StatementSyntax)
Select Case executableBlock.Kind
Case SyntaxKind.SingleLineIfStatement
singleLineIf = DirectCast(executableBlock, SingleLineIfStatementSyntax)
ifStatements = newStatements
elseStatements = If(singleLineIf.ElseClause Is Nothing, Nothing, singleLineIf.ElseClause.Statements)
Case SyntaxKind.SingleLineElseClause
singleLineIf = DirectCast(executableBlock.Parent, SingleLineIfStatementSyntax)
ifStatements = singleLineIf.Statements
elseStatements = newStatements
Case Else
Return
End Select
Dim ifStatement = SyntaxFactory.IfStatement(singleLineIf.IfKeyword, singleLineIf.Condition, singleLineIf.ThenKeyword) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
Dim elseBlockOpt = If(singleLineIf.ElseClause Is Nothing,
Nothing,
SyntaxFactory.ElseBlock(
SyntaxFactory.ElseStatement(singleLineIf.ElseClause.ElseKeyword).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker),
elseStatements) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker))
Dim [endIf] = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.IfKeyword)) _
.WithAdditionalAnnotations(annotations)
multiLineIf = SyntaxFactory.MultiLineIfBlock(
SyntaxFactory.IfStatement(singleLineIf.IfKeyword, singleLineIf.Condition, singleLineIf.ThenKeyword) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker),
ifStatements,
Nothing,
elseBlockOpt,
[endIf]) _
.WithAdditionalAnnotations(annotations)
End Sub
<Extension()>
Public Function ConvertSingleLineToMultiLineExecutableBlock(
tree As SyntaxTree,
block As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
Dim oldBlock = block
Dim newBlock = block
Dim current = block
While current.IsSingleLineExecutableBlock()
If current.Kind = SyntaxKind.SingleLineIfStatement OrElse current.Kind = SyntaxKind.SingleLineElseClause Then
Dim singleLineIf As SingleLineIfStatementSyntax = Nothing
Dim multiLineIf As MultiLineIfBlockSyntax = Nothing
UpdateStatements(current, statements, annotations, singleLineIf, multiLineIf)
statements = SyntaxFactory.List({DirectCast(multiLineIf, StatementSyntax)})
current = singleLineIf.Parent
oldBlock = singleLineIf
newBlock = multiLineIf
ElseIf current.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
Dim singleLineLambda = DirectCast(current, SingleLineLambdaExpressionSyntax)
Dim multiLineLambda = SyntaxFactory.MultiLineSubLambdaExpression(
singleLineLambda.SubOrFunctionHeader,
statements,
SyntaxFactory.EndSubStatement()).WithAdditionalAnnotations(annotations)
oldBlock = singleLineLambda
newBlock = multiLineLambda
Exit While
Else
Exit While
End If
End While
Return tree.GetRoot().ReplaceNode(oldBlock, newBlock)
End Function
<Extension()>
Public Function GetBraces(node As SyntaxNode) As (openBrace As SyntaxToken, closeBrace As SyntaxToken)
Return node.TypeSwitch(
Function(n As TypeParameterMultipleConstraintClauseSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As ObjectMemberInitializerSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As CollectionInitializerSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As SyntaxNode) CType(Nothing, (SyntaxToken, SyntaxToken)))
End Function
<Extension()>
Public Function GetParentheses(node As SyntaxNode) As ValueTuple(Of SyntaxToken, SyntaxToken)
Return node.TypeSwitch(
Function(n As TypeParameterListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ParameterListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ArrayRankSpecifierSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ParenthesizedExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As GetTypeExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As GetXmlNamespaceExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As CTypeExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As DirectCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TryCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As PredefinedCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As BinaryConditionalExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TernaryConditionalExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ArgumentListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As FunctionAggregationSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TypeArgumentListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ExternalSourceDirectiveTriviaSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ExternalChecksumDirectiveTriviaSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As SyntaxNode) CType(Nothing, (SyntaxToken, SyntaxToken)))
End Function
<Extension>
Public Function IsLeftSideOfSimpleAssignmentStatement(node As SyntaxNode) As Boolean
Return node.IsParentKind(SyntaxKind.SimpleAssignmentStatement) AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsLeftSideOfAnyAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsAnyAssignmentStatement() AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsAnyAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
SyntaxFacts.IsAssignmentStatement(node.Kind)
End Function
<Extension>
Public Function IsLeftSideOfCompoundAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsCompoundAssignmentStatement() AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsCompoundAssignmentStatement(node As SyntaxNode) As Boolean
If node IsNot Nothing Then
Select Case node.Kind
Case SyntaxKind.AddAssignmentStatement,
SyntaxKind.SubtractAssignmentStatement,
SyntaxKind.MultiplyAssignmentStatement,
SyntaxKind.DivideAssignmentStatement,
SyntaxKind.IntegerDivideAssignmentStatement,
SyntaxKind.ExponentiateAssignmentStatement,
SyntaxKind.LeftShiftAssignmentStatement,
SyntaxKind.RightShiftAssignmentStatement,
SyntaxKind.ConcatenateAssignmentStatement
Return True
End Select
End If
Return False
End Function
<Extension>
Public Function ParentingNodeContainsDiagnostics(node As SyntaxNode) As Boolean
Dim topMostStatement = node _
.AncestorsAndSelf() _
.OfType(Of ExecutableStatementSyntax) _
.LastOrDefault()
If topMostStatement IsNot Nothing Then
Return topMostStatement.ContainsDiagnostics
End If
Dim topMostExpression = node _
.AncestorsAndSelf() _
.TakeWhile(Function(n) Not TypeOf n Is StatementSyntax) _
.OfType(Of ExpressionSyntax) _
.LastOrDefault()
If topMostExpression.Parent IsNot Nothing Then
Return topMostExpression.Parent.ContainsDiagnostics
End If
Return False
End Function
<Extension()>
Public Function CheckTopLevel(node As SyntaxNode, span As TextSpan) As Boolean
Dim block = TryCast(node, MethodBlockBaseSyntax)
If block IsNot Nothing AndAlso block.ContainsInMethodBlockBody(span) Then
Return True
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
For Each declaration In field.Declarators
If declaration.Initializer IsNot Nothing AndAlso declaration.Initializer.Span.Contains(span) Then
Return True
End If
Next
End If
Dim [property] = TryCast(node, PropertyStatementSyntax)
If [property] IsNot Nothing AndAlso [property].Initializer IsNot Nothing AndAlso [property].Initializer.Span.Contains(span) Then
Return True
End If
Return False
End Function
<Extension()>
Public Function ContainsInMethodBlockBody(block As MethodBlockBaseSyntax, textSpan As TextSpan) As Boolean
If block Is Nothing Then
Return False
End If
Dim blockSpan = TextSpan.FromBounds(block.BlockStatement.Span.End, block.EndBlockStatement.SpanStart)
Return blockSpan.Contains(textSpan)
End Function
<Extension()>
Public Function GetMembers(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
Dim compilation = TryCast(node, CompilationUnitSyntax)
If compilation IsNot Nothing Then
Return compilation.Members
End If
Dim [namespace] = TryCast(node, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
Return [namespace].Members
End If
Dim type = TryCast(node, TypeBlockSyntax)
If type IsNot Nothing Then
Return type.Members
End If
Dim [enum] = TryCast(node, EnumBlockSyntax)
If [enum] IsNot Nothing Then
Return [enum].Members
End If
Return Nothing
End Function
<Extension()>
Public Function GetBodies(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.SelectMany(Function(a) a.Statements)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.SelectMany(Function(a) a.Statements)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Where(Function(d) d.Initializer IsNot Nothing).Select(Function(d) d.Initializer.Value).WhereNotNull()
End If
Dim initializer As EqualsValueSyntax = Nothing
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
initializer = [enum].Initializer
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
initializer = propStatement.Initializer
End If
If initializer IsNot Nothing AndAlso initializer.Value IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(initializer.Value)
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
<Extension()>
Public Iterator Function GetAliasImportsClauses(root As CompilationUnitSyntax) As IEnumerable(Of SimpleImportsClauseSyntax)
For i = 0 To root.Imports.Count - 1
Dim statement = root.Imports(i)
For j = 0 To statement.ImportsClauses.Count - 1
Dim importsClause = statement.ImportsClauses(j)
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Yield simpleImportsClause
End If
End If
Next
Next
End Function
<Extension>
Friend Function GetParentConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
' Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
' ParseExpression.vb (.ParsePostFixExpression).
'
' These are the parts of the expression that the ?... expression can end with. Specifically
'
' 1. x?.y.M() // invocation
' 2. x?.y and x?.y.z // member access (covered under MemberAccessExpressionSyntax below)
' 3. x?!y // dictionary access (covered under MemberAccessExpressionSyntax below)
' 4. x?.y<...> // xml access
If node.IsAnyMemberAccessExpressionName() Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
' Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
' conditional access.
While (TypeOf node Is InvocationExpressionSyntax OrElse
TypeOf node Is MemberAccessExpressionSyntax OrElse
TypeOf node Is XmlMemberAccessExpressionSyntax) AndAlso
TypeOf node.Parent IsNot ConditionalAccessExpressionSyntax
node = TryCast(node.Parent, ExpressionSyntax)
End While
' Two cases we have to care about
'
' 1. a?.b.$$c.d And
' 2. a?.b.$$c.d?.e...
'
' Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
' lower in the tree And are Not seen as we walk upwards.
'
'
' To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
' right spine (i.e. the one after `d`). Once we do this, we then see if that itself Is on the RHS of a
' another conditional, And if so we hten return the one on the left. i.e. for '2' this goes in this direction:
'
' a?.b.$$c.d?.e // it will do:
' ----->
' <---------
'
' Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
' get the root parent in a case Like:
'
' x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // It will do:
' ----->
' <---------
' <---
' <---
' <---
If TypeOf node?.Parent Is ConditionalAccessExpressionSyntax AndAlso
DirectCast(node.Parent, ConditionalAccessExpressionSyntax).Expression Is node Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
If TypeOf node?.Parent Is ConditionalAccessExpressionSyntax AndAlso
DirectCast(node.Parent, ConditionalAccessExpressionSyntax).WhenNotNull Is node Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
Return TryCast(node, ConditionalAccessExpressionSyntax)
End Function
''' <summary>
''' <see cref="ISyntaxFacts.GetRootConditionalAccessExpression"/>
''' </summary>
<Extension>
Friend Function GetRootConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
' Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
' the root. For example, if we have `a?.b` And we're on the `.b`, this will give `a?.b`. Similarly with
' `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
' sequence).
node = node.GetParentConditionalAccessExpression()
While TypeOf node?.Parent Is ConditionalAccessExpressionSyntax
Dim conditionalParent = DirectCast(node.Parent, ConditionalAccessExpressionSyntax)
If conditionalParent.WhenNotNull Is node Then
node = conditionalParent
Else
Exit While
End If
End While
Return TryCast(node, ConditionalAccessExpressionSyntax)
End Function
<Extension>
Public Function IsInExpressionTree(node As SyntaxNode,
semanticModel As SemanticModel,
expressionTypeOpt As INamedTypeSymbol,
cancellationToken As CancellationToken) As Boolean
If expressionTypeOpt IsNot Nothing Then
Dim current = node
While current IsNot Nothing
If SyntaxFacts.IsSingleLineLambdaExpression(current.Kind) OrElse
SyntaxFacts.IsMultiLineLambdaExpression(current.Kind) Then
Dim typeInfo = semanticModel.GetTypeInfo(current, cancellationToken)
If expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition) Then
Return True
End If
ElseIf TypeOf current Is OrderingSyntax OrElse
TypeOf current Is QueryClauseSyntax OrElse
TypeOf current Is FunctionAggregationSyntax OrElse
TypeOf current Is ExpressionRangeVariableSyntax Then
Dim info = semanticModel.GetSymbolInfo(current, cancellationToken)
For Each symbol In info.GetAllSymbols()
Dim method = TryCast(symbol, IMethodSymbol)
If method IsNot Nothing AndAlso
method.Parameters.Length > 0 AndAlso
expressionTypeOpt.Equals(method.Parameters(0).Type.OriginalDefinition) Then
Return True
End If
Next
End If
current = current.Parent
End While
End If
Return False
End Function
<Extension>
Public Function GetParameterList(declaration As SyntaxNode) As ParameterListSyntax
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).ParameterList
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).ParameterList
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).ParameterList
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(declaration, DeclareStatementSyntax).ParameterList
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).ParameterList
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ParameterList
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).ParameterList
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.ParameterList
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).ParameterList
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case Else
Return Nothing
End Select
End Function
<Extension>
Public Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of AttributeListSyntax)
Select Case node.Kind
Case SyntaxKind.CompilationUnit
Return SyntaxFactory.List(DirectCast(node, CompilationUnitSyntax).Attributes.SelectMany(Function(s) s.AttributeLists))
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).AttributeLists
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).AttributeLists
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).AttributeLists
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).AttributeLists
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).AttributeLists
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).AttributeLists
Case SyntaxKind.FieldDeclaration
Return DirectCast(node, FieldDeclarationSyntax).AttributeLists
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(node, MethodStatementSyntax).AttributeLists
Case SyntaxKind.SubNewStatement
Return DirectCast(node, SubNewStatementSyntax).AttributeLists
Case SyntaxKind.Parameter
Return DirectCast(node, ParameterSyntax).AttributeLists
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).AttributeLists
Case SyntaxKind.OperatorBlock
Return DirectCast(node, OperatorBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.OperatorStatement
Return DirectCast(node, OperatorStatementSyntax).AttributeLists
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).AttributeLists
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(node, AccessorBlockSyntax).AccessorStatement.AttributeLists
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(node, AccessorStatementSyntax).AttributeLists
Case Else
Return Nothing
End Select
End Function
''' <summary>
''' If "node" is the begin statement of a declaration block, return that block, otherwise
''' return node.
''' </summary>
<Extension>
Public Function GetBlockFromBegin(node As SyntaxNode) As SyntaxNode
Dim parent As SyntaxNode = node.Parent
Dim begin As SyntaxNode = Nothing
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.NamespaceBlock
begin = DirectCast(parent, NamespaceBlockSyntax).NamespaceStatement
Case SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
begin = DirectCast(parent, TypeBlockSyntax).BlockStatement
Case SyntaxKind.EnumBlock
begin = DirectCast(parent, EnumBlockSyntax).EnumStatement
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
begin = DirectCast(parent, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.PropertyBlock
begin = DirectCast(parent, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
begin = DirectCast(parent, EventBlockSyntax).EventStatement
Case SyntaxKind.VariableDeclarator
If DirectCast(parent, VariableDeclaratorSyntax).Names.Count = 1 Then
begin = node
End If
End Select
End If
If begin Is node Then
Return parent
Else
Return node
End If
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module SyntaxNodeExtensions
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsKind(kind)
End Function
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
IsKind(node.Parent, kind1, kind2)
End Function
<Extension()>
Public Function IsParentKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind) As Boolean
Return node IsNot Nothing AndAlso
IsKind(node.Parent, kind1, kind2, kind3)
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2 OrElse
node.Kind = kind3
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, kind1 As SyntaxKind, kind2 As SyntaxKind, kind3 As SyntaxKind, kind4 As SyntaxKind) As Boolean
If node Is Nothing Then
Return False
End If
Return node.Kind = kind1 OrElse
node.Kind = kind2 OrElse
node.Kind = kind3 OrElse
node.Kind = kind4
End Function
<Extension()>
Public Function IsKind(node As SyntaxNode, ParamArray kinds As SyntaxKind()) As Boolean
If node Is Nothing Then
Return False
End If
Return kinds.Contains(node.Kind())
End Function
<Extension()>
Public Function IsInConstantContext(expression As SyntaxNode) As Boolean
If expression.GetAncestor(Of ParameterSyntax)() IsNot Nothing Then
Return True
End If
' TODO(cyrusn): Add more cases
Return False
End Function
<Extension()>
Public Function IsInStaticContext(node As SyntaxNode) As Boolean
Dim containingType = node.GetAncestorOrThis(Of TypeBlockSyntax)()
If containingType.IsKind(SyntaxKind.ModuleBlock) Then
Return True
End If
Return node.GetAncestorsOrThis(Of StatementSyntax)().
SelectMany(Function(s) s.GetModifiers()).
Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
End Function
<Extension()>
Public Function IsStatementContainerNode(node As SyntaxNode) As Boolean
If node.IsExecutableBlock() Then
Return True
End If
Dim singleLineLambdaExpression = TryCast(node, SingleLineLambdaExpressionSyntax)
If singleLineLambdaExpression IsNot Nothing AndAlso TypeOf singleLineLambdaExpression.Body Is ExecutableStatementSyntax Then
Return True
End If
Return False
End Function
<Extension()>
Public Function GetStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
Contract.ThrowIfNull(node)
Contract.ThrowIfFalse(node.IsStatementContainerNode())
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Return methodBlock.Statements
End If
Dim whileBlock = TryCast(node, WhileBlockSyntax)
If whileBlock IsNot Nothing Then
Return whileBlock.Statements
End If
Dim usingBlock = TryCast(node, UsingBlockSyntax)
If usingBlock IsNot Nothing Then
Return usingBlock.Statements
End If
Dim syncLockBlock = TryCast(node, SyncLockBlockSyntax)
If syncLockBlock IsNot Nothing Then
Return syncLockBlock.Statements
End If
Dim withBlock = TryCast(node, WithBlockSyntax)
If withBlock IsNot Nothing Then
Return withBlock.Statements
End If
Dim singleLineIfStatement = TryCast(node, SingleLineIfStatementSyntax)
If singleLineIfStatement IsNot Nothing Then
Return singleLineIfStatement.Statements
End If
Dim singleLineElseClause = TryCast(node, SingleLineElseClauseSyntax)
If singleLineElseClause IsNot Nothing Then
Return singleLineElseClause.Statements
End If
Dim ifBlock = TryCast(node, MultiLineIfBlockSyntax)
If ifBlock IsNot Nothing Then
Return ifBlock.Statements
End If
Dim elseIfBlock = TryCast(node, ElseIfBlockSyntax)
If elseIfBlock IsNot Nothing Then
Return elseIfBlock.Statements
End If
Dim elseBlock = TryCast(node, ElseBlockSyntax)
If elseBlock IsNot Nothing Then
Return elseBlock.Statements
End If
Dim tryBlock = TryCast(node, TryBlockSyntax)
If tryBlock IsNot Nothing Then
Return tryBlock.Statements
End If
Dim catchBlock = TryCast(node, CatchBlockSyntax)
If catchBlock IsNot Nothing Then
Return catchBlock.Statements
End If
Dim finallyBlock = TryCast(node, FinallyBlockSyntax)
If finallyBlock IsNot Nothing Then
Return finallyBlock.Statements
End If
Dim caseBlock = TryCast(node, CaseBlockSyntax)
If caseBlock IsNot Nothing Then
Return caseBlock.Statements
End If
Dim doLoopBlock = TryCast(node, DoLoopBlockSyntax)
If doLoopBlock IsNot Nothing Then
Return doLoopBlock.Statements
End If
Dim forBlock = TryCast(node, ForOrForEachBlockSyntax)
If forBlock IsNot Nothing Then
Return forBlock.Statements
End If
Dim singleLineLambdaExpression = TryCast(node, SingleLineLambdaExpressionSyntax)
If singleLineLambdaExpression IsNot Nothing Then
Return If(TypeOf singleLineLambdaExpression.Body Is StatementSyntax,
SyntaxFactory.SingletonList(DirectCast(singleLineLambdaExpression.Body, StatementSyntax)),
Nothing)
End If
Dim multiLineLambdaExpression = TryCast(node, MultiLineLambdaExpressionSyntax)
If multiLineLambdaExpression IsNot Nothing Then
Return multiLineLambdaExpression.Statements
End If
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
<Extension()>
Friend Function IsAsyncSupportedFunctionSyntax(node As SyntaxNode) As Boolean
Select Case node?.Kind()
Case _
SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return True
End Select
Return False
End Function
<Extension()>
Friend Function IsMultiLineLambda(node As SyntaxNode) As Boolean
Return SyntaxFacts.IsMultiLineLambdaExpression(node.Kind())
End Function
<Extension()>
Friend Function GetTypeCharacterString(type As TypeCharacter) As String
Select Case type
Case TypeCharacter.Integer
Return "%"
Case TypeCharacter.Long
Return "&"
Case TypeCharacter.Decimal
Return "@"
Case TypeCharacter.Single
Return "!"
Case TypeCharacter.Double
Return "#"
Case TypeCharacter.String
Return "$"
Case Else
Throw New ArgumentException("Unexpected TypeCharacter.", NameOf(type))
End Select
End Function
<Extension()>
Public Function SpansPreprocessorDirective(Of TSyntaxNode As SyntaxNode)(list As IEnumerable(Of TSyntaxNode)) As Boolean
Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(list)
End Function
<Extension()>
Public Function ConvertToSingleLine(Of TNode As SyntaxNode)(node As TNode, Optional useElasticTrivia As Boolean = False) As TNode
If node Is Nothing Then
Return node
End If
Dim rewriter = New SingleLineRewriter(useElasticTrivia)
Return DirectCast(rewriter.Visit(node), TNode)
End Function
''' <summary>
''' Breaks up the list of provided nodes, based on how they are
''' interspersed with pp directives, into groups. Within these groups
''' nodes can be moved around safely, without breaking any pp
''' constructs.
''' </summary>
<Extension()>
Public Function SplitNodesOnPreprocessorBoundaries(Of TSyntaxNode As SyntaxNode)(
nodes As IEnumerable(Of TSyntaxNode),
cancellationToken As CancellationToken) As IList(Of IList(Of TSyntaxNode))
Dim result = New List(Of IList(Of TSyntaxNode))()
Dim currentGroup = New List(Of TSyntaxNode)()
For Each node In nodes
Dim hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken)
Dim hasLeadingDirective = node.GetLeadingTrivia().Any(Function(t) SyntaxFacts.IsPreprocessorDirective(t.Kind))
If hasUnmatchedInteriorDirective Then
' we have a #if/#endif/#region/#endregion/#else/#elif in
' this node that belongs to a span of pp directives that
' is not entirely contained within the node. i.e.:
'
' void Goo() {
' #if ...
' }
'
' This node cannot be moved at all. It is in a group that
' only contains itself (and thus can never be moved).
' add whatever group we've built up to now. And reset the
' next group to empty.
result.Add(currentGroup)
currentGroup = New List(Of TSyntaxNode)()
result.Add(New List(Of TSyntaxNode) From {node})
ElseIf hasLeadingDirective Then
' We have a PP directive before us. i.e.:
'
' #if ...
' void Goo() {
'
' That means we start a new group that is contained between
' the above directive and the following directive.
' add whatever group we've built up to now. And reset the
' next group to empty.
result.Add(currentGroup)
currentGroup = New List(Of TSyntaxNode)()
currentGroup.Add(node)
Else
' simple case. just add ourselves to the current group
currentGroup.Add(node)
End If
Next
' add the remainder of the final group.
result.Add(currentGroup)
' Now, filter out any empty groups.
result = result.Where(Function(group) Not group.IsEmpty()).ToList()
Return result
End Function
''' <summary>
''' Returns true if the passed in node contains an interleaved pp
''' directive.
'''
''' i.e. The following returns false:
'''
''' void Goo() {
''' #if true
''' #endif
''' }
'''
''' #if true
''' void Goo() {
''' }
''' #endif
'''
''' but these return true:
'''
''' #if true
''' void Goo() {
''' #endif
''' }
'''
''' void Goo() {
''' #if true
''' }
''' #endif
'''
''' #if true
''' void Goo() {
''' #else
''' }
''' #endif
'''
''' i.e. the method returns true if it contains a PP directive that
''' belongs to a grouping constructs (like #if/#endif or
''' #region/#endregion), but the grouping construct isn't entirely c
''' contained within the span of the node.
''' </summary>
<Extension()>
Public Function ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Return VisualBasicSyntaxFacts.Instance.ContainsInterleavedDirective(node, cancellationToken)
End Function
<Extension>
Public Function ContainsInterleavedDirective(
token As SyntaxToken,
textSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
Return ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) OrElse
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken)
End Function
Private Function ContainsInterleavedDirective(
textSpan As TextSpan,
list As SyntaxTriviaList,
cancellationToken As CancellationToken) As Boolean
For Each trivia In list
If textSpan.Contains(trivia.Span) Then
If ContainsInterleavedDirective(textSpan, trivia, cancellationToken) Then
Return True
End If
End If
Next trivia
Return False
End Function
Private Function ContainsInterleavedDirective(
textSpan As TextSpan,
trivia As SyntaxTrivia,
cancellationToken As CancellationToken) As Boolean
If trivia.HasStructure AndAlso TypeOf trivia.GetStructure() Is DirectiveTriviaSyntax Then
Dim parentSpan = trivia.GetStructure().Span
Dim directiveSyntax = DirectCast(trivia.GetStructure(), DirectiveTriviaSyntax)
If directiveSyntax.IsKind(SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.IfDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia) Then
Dim match = directiveSyntax.GetMatchingStartOrEndDirective(cancellationToken)
If match IsNot Nothing Then
Dim matchSpan = match.Span
If Not textSpan.Contains(matchSpan.Start) Then
' The match for this pp directive is outside
' this node.
Return True
End If
End If
ElseIf directiveSyntax.IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia) Then
Dim directives = directiveSyntax.GetMatchingConditionalDirectives(cancellationToken)
If directives IsNot Nothing AndAlso directives.Count > 0 Then
If Not textSpan.Contains(directives(0).SpanStart) OrElse
Not textSpan.Contains(directives(directives.Count - 1).SpanStart) Then
' This else/elif belongs to a pp span that isn't
' entirely within this node.
Return True
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function GetLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As ImmutableArray(Of SyntaxTrivia)
Return VisualBasicSyntaxFacts.Instance.GetLeadingBlankLines(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode, ByRef strippedTrivia As ImmutableArray(Of SyntaxTrivia)) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, strippedTrivia)
End Function
<Extension()>
Public Function GetLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As ImmutableArray(Of SyntaxTrivia)
Return VisualBasicSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node)
End Function
<Extension()>
Public Function GetNodeWithoutLeadingBannerAndPreprocessorDirectives(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode, ByRef strippedTrivia As ImmutableArray(Of SyntaxTrivia)) As TSyntaxNode
Return VisualBasicSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, strippedTrivia)
End Function
''' <summary>
''' Returns true if this is a block that can contain multiple executable statements. i.e.
''' this node is the VB equivalent of a BlockSyntax in C#.
''' </summary>
<Extension()>
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean
If node IsNot Nothing Then
If TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is DoLoopBlockSyntax OrElse
TypeOf node Is ForOrForEachBlockSyntax OrElse
TypeOf node Is MultiLineLambdaExpressionSyntax Then
Return True
End If
Select Case node.Kind
Case SyntaxKind.WhileBlock,
SyntaxKind.UsingBlock,
SyntaxKind.SyncLockBlock,
SyntaxKind.WithBlock,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.SingleLineElseClause,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineIfBlock,
SyntaxKind.ElseIfBlock,
SyntaxKind.ElseBlock,
SyntaxKind.TryBlock,
SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock,
SyntaxKind.CaseBlock,
SyntaxKind.CaseElseBlock
Return True
End Select
End If
Return False
End Function
<Extension()>
Public Function GetContainingExecutableBlocks(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return node.GetAncestorsOrThis(Of StatementSyntax).
Where(Function(s) s.Parent.IsExecutableBlock() AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).
Select(Function(s) s.Parent)
End Function
<Extension()>
Public Function GetContainingMultiLineExecutableBlocks(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return node.GetAncestorsOrThis(Of StatementSyntax).
Where(Function(s) s.Parent.IsMultiLineExecutableBlock AndAlso s.Parent.GetExecutableBlockStatements().Contains(s)).
Select(Function(s) s.Parent)
End Function
<Extension()>
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim blocks As IEnumerable(Of SyntaxNode) = Nothing
For Each node In nodes
blocks = If(blocks Is Nothing,
node.GetContainingExecutableBlocks(),
blocks.Intersect(node.GetContainingExecutableBlocks()))
Next
Return If(blocks Is Nothing, Nothing, blocks.FirstOrDefault())
End Function
<Extension()>
Public Function GetExecutableBlockStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
If node IsNot Nothing Then
If TypeOf node Is MethodBlockBaseSyntax Then
Return DirectCast(node, MethodBlockBaseSyntax).Statements
ElseIf TypeOf node Is DoLoopBlockSyntax Then
Return DirectCast(node, DoLoopBlockSyntax).Statements
ElseIf TypeOf node Is ForOrForEachBlockSyntax Then
Return DirectCast(node, ForOrForEachBlockSyntax).Statements
ElseIf TypeOf node Is MultiLineLambdaExpressionSyntax Then
Return DirectCast(node, MultiLineLambdaExpressionSyntax).Statements
End If
Select Case node.Kind
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).Statements
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).Statements
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).Statements
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).Statements
Case SyntaxKind.SingleLineIfStatement
Return DirectCast(node, SingleLineIfStatementSyntax).Statements
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).Statements
Case SyntaxKind.SingleLineSubLambdaExpression
Return SyntaxFactory.SingletonList(DirectCast(DirectCast(node, SingleLineLambdaExpressionSyntax).Body, StatementSyntax))
Case SyntaxKind.MultiLineIfBlock
Return DirectCast(node, MultiLineIfBlockSyntax).Statements
Case SyntaxKind.ElseIfBlock
Return DirectCast(node, ElseIfBlockSyntax).Statements
Case SyntaxKind.ElseBlock
Return DirectCast(node, ElseBlockSyntax).Statements
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).Statements
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).Statements
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).Statements
Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock
Return DirectCast(node, CaseBlockSyntax).Statements
End Select
End If
Return Nothing
End Function
''' <summary>
''' Returns child node or token that contains given position.
''' </summary>
''' <remarks>
''' This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
''' </remarks>
<Extension>
Friend Function ChildThatContainsPosition(self As SyntaxNode, position As Integer, ByRef childIndex As Integer) As SyntaxNodeOrToken
Dim childList = self.ChildNodesAndTokens()
Dim left As Integer = 0
Dim right As Integer = childList.Count - 1
While left <= right
Dim middle As Integer = left + (right - left) \ 2
Dim node As SyntaxNodeOrToken = childList(middle)
Dim span = node.FullSpan
If position < span.Start Then
right = middle - 1
ElseIf position >= span.End Then
left = middle + 1
Else
childIndex = middle
Return node
End If
End While
Debug.Assert(Not self.FullSpan.Contains(position), "Position is valid. How could we not find a child?")
Throw New ArgumentOutOfRangeException(NameOf(position))
End Function
<Extension()>
Public Function ReplaceStatements(node As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
Return node.TypeSwitch(
Function(x As MethodBlockSyntax) x.WithStatements(statements),
Function(x As ConstructorBlockSyntax) x.WithStatements(statements),
Function(x As OperatorBlockSyntax) x.WithStatements(statements),
Function(x As AccessorBlockSyntax) x.WithStatements(statements),
Function(x As DoLoopBlockSyntax) x.WithStatements(statements),
Function(x As ForBlockSyntax) x.WithStatements(statements),
Function(x As ForEachBlockSyntax) x.WithStatements(statements),
Function(x As MultiLineLambdaExpressionSyntax) x.WithStatements(statements),
Function(x As WhileBlockSyntax) x.WithStatements(statements),
Function(x As UsingBlockSyntax) x.WithStatements(statements),
Function(x As SyncLockBlockSyntax) x.WithStatements(statements),
Function(x As WithBlockSyntax) x.WithStatements(statements),
Function(x As SingleLineIfStatementSyntax) x.WithStatements(statements),
Function(x As SingleLineElseClauseSyntax) x.WithStatements(statements),
Function(x As SingleLineLambdaExpressionSyntax) ReplaceSingleLineLambdaExpressionStatements(x, statements, annotations),
Function(x As MultiLineIfBlockSyntax) x.WithStatements(statements),
Function(x As ElseIfBlockSyntax) x.WithStatements(statements),
Function(x As ElseBlockSyntax) x.WithStatements(statements),
Function(x As TryBlockSyntax) x.WithStatements(statements),
Function(x As CatchBlockSyntax) x.WithStatements(statements),
Function(x As FinallyBlockSyntax) x.WithStatements(statements),
Function(x As CaseBlockSyntax) x.WithStatements(statements))
End Function
<Extension()>
Public Function ReplaceSingleLineLambdaExpressionStatements(
node As SingleLineLambdaExpressionSyntax,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
Dim singleLineLambda = DirectCast(node, SingleLineLambdaExpressionSyntax)
If statements.Count = 1 Then
Return node.WithBody(statements.First())
Else
#If False Then
Dim statementsAndSeparators = statements.GetWithSeparators()
If statementsAndSeparators.LastOrDefault().IsNode Then
statements = Syntax.SeparatedList(Of StatementSyntax)(
statementsAndSeparators.Concat(Syntax.Token(SyntaxKind.StatementTerminatorToken)))
End If
#End If
Return SyntaxFactory.MultiLineSubLambdaExpression(
singleLineLambda.SubOrFunctionHeader,
statements,
SyntaxFactory.EndSubStatement()).WithAdditionalAnnotations(annotations)
End If
End If
' Can't be called on a single line lambda (as it can't have statements for children)
Throw New InvalidOperationException()
End Function
<Extension()>
Public Function ReplaceStatements(tree As SyntaxTree,
executableBlock As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
If executableBlock.IsSingleLineExecutableBlock() Then
Return ConvertSingleLineToMultiLineExecutableBlock(tree, executableBlock, statements, annotations)
End If
' TODO(cyrusn): Implement this.
Throw ExceptionUtilities.Unreachable
End Function
<Extension()>
Public Function IsSingleLineExecutableBlock(executableBlock As SyntaxNode) As Boolean
Select Case executableBlock.Kind
Case SyntaxKind.SingleLineElseClause,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.SingleLineSubLambdaExpression
Return executableBlock.GetExecutableBlockStatements().Count = 1
Case Else
Return False
End Select
End Function
<Extension()>
Public Function IsMultiLineExecutableBlock(node As SyntaxNode) As Boolean
Return node.IsExecutableBlock AndAlso Not node.IsSingleLineExecutableBlock
End Function
Private Sub UpdateStatements(executableBlock As SyntaxNode,
newStatements As SyntaxList(Of StatementSyntax),
annotations As SyntaxAnnotation(),
ByRef singleLineIf As SingleLineIfStatementSyntax,
ByRef multiLineIf As MultiLineIfBlockSyntax)
Dim ifStatements As SyntaxList(Of StatementSyntax)
Dim elseStatements As SyntaxList(Of StatementSyntax)
Select Case executableBlock.Kind
Case SyntaxKind.SingleLineIfStatement
singleLineIf = DirectCast(executableBlock, SingleLineIfStatementSyntax)
ifStatements = newStatements
elseStatements = If(singleLineIf.ElseClause Is Nothing, Nothing, singleLineIf.ElseClause.Statements)
Case SyntaxKind.SingleLineElseClause
singleLineIf = DirectCast(executableBlock.Parent, SingleLineIfStatementSyntax)
ifStatements = singleLineIf.Statements
elseStatements = newStatements
Case Else
Return
End Select
Dim ifStatement = SyntaxFactory.IfStatement(singleLineIf.IfKeyword, singleLineIf.Condition, singleLineIf.ThenKeyword) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
Dim elseBlockOpt = If(singleLineIf.ElseClause Is Nothing,
Nothing,
SyntaxFactory.ElseBlock(
SyntaxFactory.ElseStatement(singleLineIf.ElseClause.ElseKeyword).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker),
elseStatements) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker))
Dim [endIf] = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.IfKeyword)) _
.WithAdditionalAnnotations(annotations)
multiLineIf = SyntaxFactory.MultiLineIfBlock(
SyntaxFactory.IfStatement(singleLineIf.IfKeyword, singleLineIf.Condition, singleLineIf.ThenKeyword) _
.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker),
ifStatements,
Nothing,
elseBlockOpt,
[endIf]) _
.WithAdditionalAnnotations(annotations)
End Sub
<Extension()>
Public Function ConvertSingleLineToMultiLineExecutableBlock(
tree As SyntaxTree,
block As SyntaxNode,
statements As SyntaxList(Of StatementSyntax),
ParamArray annotations As SyntaxAnnotation()) As SyntaxNode
Dim oldBlock = block
Dim newBlock = block
Dim current = block
While current.IsSingleLineExecutableBlock()
If current.Kind = SyntaxKind.SingleLineIfStatement OrElse current.Kind = SyntaxKind.SingleLineElseClause Then
Dim singleLineIf As SingleLineIfStatementSyntax = Nothing
Dim multiLineIf As MultiLineIfBlockSyntax = Nothing
UpdateStatements(current, statements, annotations, singleLineIf, multiLineIf)
statements = SyntaxFactory.List({DirectCast(multiLineIf, StatementSyntax)})
current = singleLineIf.Parent
oldBlock = singleLineIf
newBlock = multiLineIf
ElseIf current.Kind = SyntaxKind.SingleLineSubLambdaExpression Then
Dim singleLineLambda = DirectCast(current, SingleLineLambdaExpressionSyntax)
Dim multiLineLambda = SyntaxFactory.MultiLineSubLambdaExpression(
singleLineLambda.SubOrFunctionHeader,
statements,
SyntaxFactory.EndSubStatement()).WithAdditionalAnnotations(annotations)
oldBlock = singleLineLambda
newBlock = multiLineLambda
Exit While
Else
Exit While
End If
End While
Return tree.GetRoot().ReplaceNode(oldBlock, newBlock)
End Function
<Extension()>
Public Function GetBraces(node As SyntaxNode) As (openBrace As SyntaxToken, closeBrace As SyntaxToken)
Return node.TypeSwitch(
Function(n As TypeParameterMultipleConstraintClauseSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As ObjectMemberInitializerSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As CollectionInitializerSyntax) (n.OpenBraceToken, n.CloseBraceToken),
Function(n As SyntaxNode) CType(Nothing, (SyntaxToken, SyntaxToken)))
End Function
<Extension()>
Public Function GetParentheses(node As SyntaxNode) As ValueTuple(Of SyntaxToken, SyntaxToken)
Return node.TypeSwitch(
Function(n As TypeParameterListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ParameterListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ArrayRankSpecifierSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ParenthesizedExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As GetTypeExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As GetXmlNamespaceExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As CTypeExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As DirectCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TryCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As PredefinedCastExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As BinaryConditionalExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TernaryConditionalExpressionSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ArgumentListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As FunctionAggregationSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As TypeArgumentListSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ExternalSourceDirectiveTriviaSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As ExternalChecksumDirectiveTriviaSyntax) (n.OpenParenToken, n.CloseParenToken),
Function(n As SyntaxNode) CType(Nothing, (SyntaxToken, SyntaxToken)))
End Function
<Extension>
Public Function IsLeftSideOfSimpleAssignmentStatement(node As SyntaxNode) As Boolean
Return node.IsParentKind(SyntaxKind.SimpleAssignmentStatement) AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsLeftSideOfAnyAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsAnyAssignmentStatement() AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsAnyAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
SyntaxFacts.IsAssignmentStatement(node.Kind)
End Function
<Extension>
Public Function IsLeftSideOfCompoundAssignmentStatement(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso
node.Parent.IsCompoundAssignmentStatement() AndAlso
DirectCast(node.Parent, AssignmentStatementSyntax).Left Is node
End Function
<Extension>
Public Function IsCompoundAssignmentStatement(node As SyntaxNode) As Boolean
If node IsNot Nothing Then
Select Case node.Kind
Case SyntaxKind.AddAssignmentStatement,
SyntaxKind.SubtractAssignmentStatement,
SyntaxKind.MultiplyAssignmentStatement,
SyntaxKind.DivideAssignmentStatement,
SyntaxKind.IntegerDivideAssignmentStatement,
SyntaxKind.ExponentiateAssignmentStatement,
SyntaxKind.LeftShiftAssignmentStatement,
SyntaxKind.RightShiftAssignmentStatement,
SyntaxKind.ConcatenateAssignmentStatement
Return True
End Select
End If
Return False
End Function
<Extension>
Public Function ParentingNodeContainsDiagnostics(node As SyntaxNode) As Boolean
Dim topMostStatement = node _
.AncestorsAndSelf() _
.OfType(Of ExecutableStatementSyntax) _
.LastOrDefault()
If topMostStatement IsNot Nothing Then
Return topMostStatement.ContainsDiagnostics
End If
Dim topMostExpression = node _
.AncestorsAndSelf() _
.TakeWhile(Function(n) Not TypeOf n Is StatementSyntax) _
.OfType(Of ExpressionSyntax) _
.LastOrDefault()
If topMostExpression.Parent IsNot Nothing Then
Return topMostExpression.Parent.ContainsDiagnostics
End If
Return False
End Function
<Extension()>
Public Function CheckTopLevel(node As SyntaxNode, span As TextSpan) As Boolean
Dim block = TryCast(node, MethodBlockBaseSyntax)
If block IsNot Nothing AndAlso block.ContainsInMethodBlockBody(span) Then
Return True
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
For Each declaration In field.Declarators
If declaration.Initializer IsNot Nothing AndAlso declaration.Initializer.Span.Contains(span) Then
Return True
End If
Next
End If
Dim [property] = TryCast(node, PropertyStatementSyntax)
If [property] IsNot Nothing AndAlso [property].Initializer IsNot Nothing AndAlso [property].Initializer.Span.Contains(span) Then
Return True
End If
Return False
End Function
<Extension()>
Public Function ContainsInMethodBlockBody(block As MethodBlockBaseSyntax, textSpan As TextSpan) As Boolean
If block Is Nothing Then
Return False
End If
Dim blockSpan = TextSpan.FromBounds(block.BlockStatement.Span.End, block.EndBlockStatement.SpanStart)
Return blockSpan.Contains(textSpan)
End Function
<Extension()>
Public Function GetMembers(node As SyntaxNode) As SyntaxList(Of StatementSyntax)
Dim compilation = TryCast(node, CompilationUnitSyntax)
If compilation IsNot Nothing Then
Return compilation.Members
End If
Dim [namespace] = TryCast(node, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
Return [namespace].Members
End If
Dim type = TryCast(node, TypeBlockSyntax)
If type IsNot Nothing Then
Return type.Members
End If
Dim [enum] = TryCast(node, EnumBlockSyntax)
If [enum] IsNot Nothing Then
Return [enum].Members
End If
Return Nothing
End Function
<Extension()>
Public Function GetBodies(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.SelectMany(Function(a) a.Statements)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.SelectMany(Function(a) a.Statements)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Where(Function(d) d.Initializer IsNot Nothing).Select(Function(d) d.Initializer.Value).WhereNotNull()
End If
Dim initializer As EqualsValueSyntax = Nothing
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
initializer = [enum].Initializer
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
initializer = propStatement.Initializer
End If
If initializer IsNot Nothing AndAlso initializer.Value IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(initializer.Value)
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
<Extension()>
Public Iterator Function GetAliasImportsClauses(root As CompilationUnitSyntax) As IEnumerable(Of SimpleImportsClauseSyntax)
For i = 0 To root.Imports.Count - 1
Dim statement = root.Imports(i)
For j = 0 To statement.ImportsClauses.Count - 1
Dim importsClause = statement.ImportsClauses(j)
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Yield simpleImportsClause
End If
End If
Next
Next
End Function
<Extension>
Friend Function GetParentConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
' Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
' ParseExpression.vb (.ParsePostFixExpression).
'
' These are the parts of the expression that the ?... expression can end with. Specifically
'
' 1. x?.y.M() // invocation
' 2. x?.y and x?.y.z // member access (covered under MemberAccessExpressionSyntax below)
' 3. x?!y // dictionary access (covered under MemberAccessExpressionSyntax below)
' 4. x?.y<...> // xml access
If node.IsAnyMemberAccessExpressionName() Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
' Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
' conditional access.
While (TypeOf node Is InvocationExpressionSyntax OrElse
TypeOf node Is MemberAccessExpressionSyntax OrElse
TypeOf node Is XmlMemberAccessExpressionSyntax) AndAlso
TypeOf node.Parent IsNot ConditionalAccessExpressionSyntax
node = TryCast(node.Parent, ExpressionSyntax)
End While
' Two cases we have to care about
'
' 1. a?.b.$$c.d And
' 2. a?.b.$$c.d?.e...
'
' Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
' lower in the tree And are Not seen as we walk upwards.
'
'
' To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
' right spine (i.e. the one after `d`). Once we do this, we then see if that itself Is on the RHS of a
' another conditional, And if so we hten return the one on the left. i.e. for '2' this goes in this direction:
'
' a?.b.$$c.d?.e // it will do:
' ----->
' <---------
'
' Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
' get the root parent in a case Like:
'
' x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // It will do:
' ----->
' <---------
' <---
' <---
' <---
If TypeOf node?.Parent Is ConditionalAccessExpressionSyntax AndAlso
DirectCast(node.Parent, ConditionalAccessExpressionSyntax).Expression Is node Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
If TypeOf node?.Parent Is ConditionalAccessExpressionSyntax AndAlso
DirectCast(node.Parent, ConditionalAccessExpressionSyntax).WhenNotNull Is node Then
node = DirectCast(node.Parent, ExpressionSyntax)
End If
Return TryCast(node, ConditionalAccessExpressionSyntax)
End Function
''' <summary>
''' <see cref="ISyntaxFacts.GetRootConditionalAccessExpression"/>
''' </summary>
<Extension>
Friend Function GetRootConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
' Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
' the root. For example, if we have `a?.b` And we're on the `.b`, this will give `a?.b`. Similarly with
' `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
' sequence).
node = node.GetParentConditionalAccessExpression()
While TypeOf node?.Parent Is ConditionalAccessExpressionSyntax
Dim conditionalParent = DirectCast(node.Parent, ConditionalAccessExpressionSyntax)
If conditionalParent.WhenNotNull Is node Then
node = conditionalParent
Else
Exit While
End If
End While
Return TryCast(node, ConditionalAccessExpressionSyntax)
End Function
<Extension>
Public Function IsInExpressionTree(node As SyntaxNode,
semanticModel As SemanticModel,
expressionTypeOpt As INamedTypeSymbol,
cancellationToken As CancellationToken) As Boolean
If expressionTypeOpt IsNot Nothing Then
Dim current = node
While current IsNot Nothing
If SyntaxFacts.IsSingleLineLambdaExpression(current.Kind) OrElse
SyntaxFacts.IsMultiLineLambdaExpression(current.Kind) Then
Dim typeInfo = semanticModel.GetTypeInfo(current, cancellationToken)
If expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition) Then
Return True
End If
ElseIf TypeOf current Is OrderingSyntax OrElse
TypeOf current Is QueryClauseSyntax OrElse
TypeOf current Is FunctionAggregationSyntax OrElse
TypeOf current Is ExpressionRangeVariableSyntax Then
Dim info = semanticModel.GetSymbolInfo(current, cancellationToken)
For Each symbol In info.GetAllSymbols()
Dim method = TryCast(symbol, IMethodSymbol)
If method IsNot Nothing AndAlso
method.Parameters.Length > 0 AndAlso
expressionTypeOpt.Equals(method.Parameters(0).Type.OriginalDefinition) Then
Return True
End If
Next
End If
current = current.Parent
End While
End If
Return False
End Function
<Extension>
Public Function GetParameterList(declaration As SyntaxNode) As ParameterListSyntax
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).ParameterList
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).ParameterList
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).ParameterList
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(declaration, DeclareStatementSyntax).ParameterList
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).ParameterList
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ParameterList
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).ParameterList
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.ParameterList
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).ParameterList
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case Else
Return Nothing
End Select
End Function
<Extension>
Public Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of AttributeListSyntax)
Select Case node.Kind
Case SyntaxKind.CompilationUnit
Return SyntaxFactory.List(DirectCast(node, CompilationUnitSyntax).Attributes.SelectMany(Function(s) s.AttributeLists))
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).AttributeLists
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).AttributeLists
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).AttributeLists
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).AttributeLists
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).AttributeLists
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).AttributeLists
Case SyntaxKind.FieldDeclaration
Return DirectCast(node, FieldDeclarationSyntax).AttributeLists
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(node, MethodStatementSyntax).AttributeLists
Case SyntaxKind.SubNewStatement
Return DirectCast(node, SubNewStatementSyntax).AttributeLists
Case SyntaxKind.Parameter
Return DirectCast(node, ParameterSyntax).AttributeLists
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).AttributeLists
Case SyntaxKind.OperatorBlock
Return DirectCast(node, OperatorBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.OperatorStatement
Return DirectCast(node, OperatorStatementSyntax).AttributeLists
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).AttributeLists
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(node, AccessorBlockSyntax).AccessorStatement.AttributeLists
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(node, AccessorStatementSyntax).AttributeLists
Case Else
Return Nothing
End Select
End Function
''' <summary>
''' If "node" is the begin statement of a declaration block, return that block, otherwise
''' return node.
''' </summary>
<Extension>
Public Function GetBlockFromBegin(node As SyntaxNode) As SyntaxNode
Dim parent As SyntaxNode = node.Parent
Dim begin As SyntaxNode = Nothing
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.NamespaceBlock
begin = DirectCast(parent, NamespaceBlockSyntax).NamespaceStatement
Case SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
begin = DirectCast(parent, TypeBlockSyntax).BlockStatement
Case SyntaxKind.EnumBlock
begin = DirectCast(parent, EnumBlockSyntax).EnumStatement
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
begin = DirectCast(parent, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.PropertyBlock
begin = DirectCast(parent, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
begin = DirectCast(parent, EventBlockSyntax).EventStatement
Case SyntaxKind.VariableDeclarator
If DirectCast(parent, VariableDeclaratorSyntax).Names.Count = 1 Then
begin = node
End If
End Select
End If
If begin Is node Then
Return parent
Else
Return node
End If
End Function
<Extension>
Public Function GetDeclarationBlockFromBegin(node As DeclarationStatementSyntax) As DeclarationStatementSyntax
Dim parent As SyntaxNode = node.Parent
Dim begin As SyntaxNode = Nothing
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.NamespaceBlock
begin = DirectCast(parent, NamespaceBlockSyntax).NamespaceStatement
Case SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
begin = DirectCast(parent, TypeBlockSyntax).BlockStatement
Case SyntaxKind.EnumBlock
begin = DirectCast(parent, EnumBlockSyntax).EnumStatement
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
begin = DirectCast(parent, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.PropertyBlock
begin = DirectCast(parent, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
begin = DirectCast(parent, EventBlockSyntax).EventStatement
End Select
End If
If begin Is node Then
' Every one of these parent casts is of a subtype of DeclarationStatementSyntax
' So if the cast worked above, it will work here
Return DirectCast(parent, DeclarationStatementSyntax)
Else
Return node
End If
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/EventGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module EventGenerator
Private Function AfterMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
If eventDeclaration.Kind = SyntaxKind.EventStatement Then
' Field style events go after the last field event, or after the last field.
Dim lastEvent = members.LastOrDefault(Function(m) TypeOf m Is EventStatementSyntax)
Return If(lastEvent, LastField(members))
End If
If eventDeclaration.Kind = SyntaxKind.EventBlock Then
' Property style events go after existing events, then after existing constructors.
Dim lastEvent = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.EventBlock)
Return If(lastEvent, LastConstructor(members))
End If
Return Nothing
End Function
Private Function BeforeMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
' If it's a field style event, then it goes before everything else if we don't have any
' existing fields/events.
If eventDeclaration.Kind = SyntaxKind.FieldDeclaration Then
Return members.FirstOrDefault()
End If
' Otherwise just place it before the methods.
Return FirstMethod(members)
End Function
Friend Function AddEventTo(destination As TypeBlockSyntax,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim eventDeclaration = GenerateEventDeclaration([event], GetDestination(destination), options)
Dim members = Insert(destination.Members, eventDeclaration, options, availableIndices,
after:=Function(list) AfterMember(list, eventDeclaration),
before:=Function(list) BeforeMember(list, eventDeclaration))
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([event], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GenerateEventDeclarationWorker([event], destination, options)
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, [event], options))
End Function
Private Function GenerateEventDeclarationWorker([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
If options.GenerateMethodBodies AndAlso
([event].AddMethod IsNot Nothing OrElse [event].RemoveMethod IsNot Nothing OrElse [event].RaiseMethod IsNot Nothing) Then
Return GenerateCustomEventDeclarationWorker([event], destination, options)
Else
Return GenerateNotCustomEventDeclarationWorker([event], destination, options)
End If
End Function
Private Function GenerateCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim addStatements = If(
[event].AddMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].AddMethod))
Dim removeStatements = If(
[event].RemoveMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RemoveMethod))
Dim raiseStatements = If(
[event].RaiseMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RaiseMethod))
Dim generator As VisualBasicSyntaxGenerator = New VisualBasicSyntaxGenerator()
Dim invoke = DirectCast([event].Type, INamedTypeSymbol)?.DelegateInvokeMethod
Dim parameters = If(
invoke IsNot Nothing,
invoke.Parameters.Select(Function(p) generator.ParameterDeclaration(p)),
Nothing)
Dim result = DirectCast(generator.CustomEventDeclarationWithRaise(
[event].Name,
generator.TypeExpression([event].Type),
[event].DeclaredAccessibility,
DeclarationModifiers.From([event]),
parameters,
addStatements,
removeStatements,
raiseStatements), EventBlockSyntax)
result = DirectCast(
result.WithAttributeLists(GenerateAttributeBlocks([event].GetAttributes(), options)),
EventBlockSyntax)
result = DirectCast(result.WithModifiers(GenerateModifiers([event], destination, options)), EventBlockSyntax)
Dim explicitInterface = [event].ExplicitInterfaceImplementations.FirstOrDefault()
If (explicitInterface IsNot Nothing)
result = result.WithEventStatement(
result.EventStatement.WithImplementsClause(GenerateImplementsClause(explicitInterface)))
End If
Return result
End Function
Private Function GenerateNotCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As EventStatementSyntax
Dim eventType = TryCast([event].Type, INamedTypeSymbol)
If eventType.IsDelegateType() AndAlso eventType.AssociatedSymbol IsNot Nothing Then
' This is a declaration style event like "Event E(x As String)". This event will
' have a type that is unmentionable. So we should not generate it as "Event E() As
' SomeType", but should instead inline the delegate type into the event itself.
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=ParameterGenerator.GenerateParameterList(eventType.DelegateInvokeMethod.Parameters.Select(Function(p) RemoveOptionalOrParamArray(p)).ToList(), options),
asClause:=Nothing,
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End If
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=Nothing,
asClause:=GenerateAsClause([event]),
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End Function
Private Function GenerateModifiers([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([event].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [event].IsStatic Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If [event].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function GenerateAsClause([event] As IEventSymbol) As SimpleAsClauseSyntax
' TODO: Someday support events without as clauses (with parameter lists instead)
Return SyntaxFactory.SimpleAsClause([event].Type.GenerateTypeSyntax())
End Function
Private Function RemoveOptionalOrParamArray(parameter As IParameterSymbol) As IParameterSymbol
If Not parameter.IsOptional AndAlso Not parameter.IsParams Then
Return parameter
Else
Return CodeGenerationSymbolFactory.CreateParameterSymbol(parameter.GetAttributes(), parameter.RefKind, isParams:=False, type:=parameter.Type, name:=parameter.Name, hasDefaultValue:=False)
End If
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module EventGenerator
Private Function AfterMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
If eventDeclaration.Kind = SyntaxKind.EventStatement Then
' Field style events go after the last field event, or after the last field.
Dim lastEvent = members.LastOrDefault(Function(m) TypeOf m Is EventStatementSyntax)
Return If(lastEvent, LastField(members))
End If
If eventDeclaration.Kind = SyntaxKind.EventBlock Then
' Property style events go after existing events, then after existing constructors.
Dim lastEvent = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.EventBlock)
Return If(lastEvent, LastConstructor(members))
End If
Return Nothing
End Function
Private Function BeforeMember(
members As SyntaxList(Of StatementSyntax),
eventDeclaration As StatementSyntax) As StatementSyntax
' If it's a field style event, then it goes before everything else if we don't have any
' existing fields/events.
If eventDeclaration.Kind = SyntaxKind.FieldDeclaration Then
Return members.FirstOrDefault()
End If
' Otherwise just place it before the methods.
Return FirstMethod(members)
End Function
Friend Function AddEventTo(destination As TypeBlockSyntax,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim eventDeclaration = GenerateEventDeclaration([event], GetDestination(destination), options)
Dim members = Insert(destination.Members, eventDeclaration, options, availableIndices,
after:=Function(list) AfterMember(list, eventDeclaration),
before:=Function(list) BeforeMember(list, eventDeclaration))
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GenerateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([event], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GenerateEventDeclarationWorker([event], destination, options)
Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, [event], options))
End Function
Private Function GenerateEventDeclarationWorker([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
If options.GenerateMethodBodies AndAlso
([event].AddMethod IsNot Nothing OrElse [event].RemoveMethod IsNot Nothing OrElse [event].RaiseMethod IsNot Nothing) Then
Return GenerateCustomEventDeclarationWorker([event], destination, options)
Else
Return GenerateNotCustomEventDeclarationWorker([event], destination, options)
End If
End Function
Private Function GenerateCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As DeclarationStatementSyntax
Dim addStatements = If(
[event].AddMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].AddMethod))
Dim removeStatements = If(
[event].RemoveMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RemoveMethod))
Dim raiseStatements = If(
[event].RaiseMethod Is Nothing,
New SyntaxList(Of StatementSyntax),
GenerateStatements([event].RaiseMethod))
Dim generator As VisualBasicSyntaxGenerator = New VisualBasicSyntaxGenerator()
Dim invoke = DirectCast([event].Type, INamedTypeSymbol)?.DelegateInvokeMethod
Dim parameters = If(
invoke IsNot Nothing,
invoke.Parameters.Select(Function(p) generator.ParameterDeclaration(p)),
Nothing)
Dim result = DirectCast(generator.CustomEventDeclarationWithRaise(
[event].Name,
generator.TypeExpression([event].Type),
[event].DeclaredAccessibility,
DeclarationModifiers.From([event]),
parameters,
addStatements,
removeStatements,
raiseStatements), EventBlockSyntax)
result = DirectCast(
result.WithAttributeLists(GenerateAttributeBlocks([event].GetAttributes(), options)),
EventBlockSyntax)
result = DirectCast(result.WithModifiers(GenerateModifiers([event], destination, options)), EventBlockSyntax)
Dim explicitInterface = [event].ExplicitInterfaceImplementations.FirstOrDefault()
If (explicitInterface IsNot Nothing)
result = result.WithEventStatement(
result.EventStatement.WithImplementsClause(GenerateImplementsClause(explicitInterface)))
End If
Return result
End Function
Private Function GenerateNotCustomEventDeclarationWorker(
[event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As EventStatementSyntax
Dim eventType = TryCast([event].Type, INamedTypeSymbol)
If eventType.IsDelegateType() AndAlso eventType.AssociatedSymbol IsNot Nothing Then
' This is a declaration style event like "Event E(x As String)". This event will
' have a type that is unmentionable. So we should not generate it as "Event E() As
' SomeType", but should instead inline the delegate type into the event itself.
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=ParameterGenerator.GenerateParameterList(eventType.DelegateInvokeMethod.Parameters.Select(Function(p) RemoveOptionalOrParamArray(p)).ToList(), options),
asClause:=Nothing,
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End If
Return SyntaxFactory.EventStatement(
attributeLists:=GenerateAttributeBlocks([event].GetAttributes(), options),
modifiers:=GenerateModifiers([event], destination, options),
identifier:=[event].Name.ToIdentifierToken,
parameterList:=Nothing,
asClause:=GenerateAsClause([event]),
implementsClause:=GenerateImplementsClause([event].ExplicitInterfaceImplementations.FirstOrDefault()))
End Function
Private Function GenerateModifiers([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([event].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [event].IsStatic Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If [event].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function GenerateAsClause([event] As IEventSymbol) As SimpleAsClauseSyntax
' TODO: Someday support events without as clauses (with parameter lists instead)
Return SyntaxFactory.SimpleAsClause([event].Type.GenerateTypeSyntax())
End Function
Private Function RemoveOptionalOrParamArray(parameter As IParameterSymbol) As IParameterSymbol
If Not parameter.IsOptional AndAlso Not parameter.IsParams Then
Return parameter
Else
Return CodeGenerationSymbolFactory.CreateParameterSymbol(parameter.GetAttributes(), parameter.RefKind, isParams:=False, type:=parameter.Type, name:=parameter.Name, hasDefaultValue:=False)
End If
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/MethodGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class MethodGenerator
Friend Shared Function AddMethodTo(destination As NamespaceBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As NamespaceBlockSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As CompilationUnitSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As TypeBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options)
Dim members = Insert(destination.Members, methodDeclaration, options, availableIndices,
after:=AddressOf LastMethod)
Return FixTerminators(destination.WithMembers(members))
End Function
Public Shared Function GenerateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(method, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GenerateMethodDeclarationWorker(method, destination, options)
Return AddAnnotationsTo(method,
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, method, options)))
End Function
Private Shared Function GenerateMethodDeclarationWorker(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim isSub = method.ReturnType.SpecialType = SpecialType.System_Void
Dim kind = If(isSub, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement)
Dim keyword = If(isSub, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword)
Dim asClauseOpt = GenerateAsClause(method, isSub, options)
Dim implementsClauseOpt = GenerateImplementsClause(method.ExplicitInterfaceImplementations.FirstOrDefault())
Dim handlesClauseOpt = GenerateHandlesClause(CodeGenerationMethodInfo.GetHandlesExpressions(method))
Dim begin =
SyntaxFactory.MethodStatement(kind, subOrFunctionKeyword:=SyntaxFactory.Token(keyword), identifier:=method.Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(method.GetAttributes(), options)).
WithModifiers(GenerateModifiers(method, destination, options)).
WithTypeParameterList(GenerateTypeParameterList(method)).
WithParameterList(ParameterGenerator.GenerateParameterList(method.Parameters, options)).
WithAsClause(asClauseOpt).
WithImplementsClause(implementsClauseOpt).
WithHandlesClause(handlesClauseOpt)
Dim hasNoBody = Not options.GenerateMethodBodies OrElse
method.IsAbstract OrElse
destination = CodeGenerationDestination.InterfaceType
If hasNoBody Then
Return begin
End If
Dim endConstruct = If(isSub, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())
Return SyntaxFactory.MethodBlock(
If(isSub, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
begin,
statements:=StatementGenerator.GenerateStatements(method),
endSubOrFunctionStatement:=endConstruct)
End Function
Private Shared Function GenerateAsClause(method As IMethodSymbol, isSub As Boolean, options As CodeGenerationOptions) As SimpleAsClauseSyntax
If isSub Then
Return Nothing
End If
Return SyntaxFactory.SimpleAsClause(
AttributeGenerator.GenerateAttributeBlocks(method.GetReturnTypeAttributes(), options),
method.ReturnType.GenerateTypeSyntax())
End Function
Private Shared Function GenerateHandlesClause(expressions As IList(Of SyntaxNode)) As HandlesClauseSyntax
Dim memberAccessExpressions = expressions.OfType(Of MemberAccessExpressionSyntax).ToList()
Dim items = From def In memberAccessExpressions
Let expr1 = def.Expression
Where expr1 IsNot Nothing
Let expr2 = If(TypeOf expr1 Is ParenthesizedExpressionSyntax, DirectCast(expr1, ParenthesizedExpressionSyntax).Expression, expr1)
Let children = expr2.ChildNodesAndTokens()
Where children.Count = 1 AndAlso children(0).IsToken
Let token = children(0).AsToken()
Where token.Kind = SyntaxKind.IdentifierToken OrElse
token.Kind = SyntaxKind.MyBaseKeyword OrElse
token.Kind = SyntaxKind.MyClassKeyword OrElse
token.Kind = SyntaxKind.MeKeyword
Where TypeOf def.Name Is IdentifierNameSyntax
Let identifier = def.Name.Identifier.ValueText.ToIdentifierName()
Select SyntaxFactory.HandlesClauseItem(If(token.Kind = SyntaxKind.IdentifierToken,
DirectCast(SyntaxFactory.WithEventsEventContainer(token.ValueText.ToIdentifierToken()), EventContainerSyntax),
SyntaxFactory.KeywordEventContainer(token)), identifier)
Dim array = items.ToArray()
Return If(array.Length = 0, Nothing, SyntaxFactory.HandlesClause(array))
End Function
Private Overloads Shared Function GenerateTypeParameterList(method As IMethodSymbol) As TypeParameterListSyntax
Return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters)
End Function
Private Shared Function GenerateModifiers(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim result As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(result)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers(method.DeclaredAccessibility, result, destination, options, Accessibility.Public)
If method.IsAbstract Then
result.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If method.IsSealed Then
result.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
If method.IsVirtual Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If method.IsOverride Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If method.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
result.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationMethodInfo.GetIsNew(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If CodeGenerationMethodInfo.GetIsAsyncMethod(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
End If
End If
Return SyntaxFactory.TokenList(result)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class MethodGenerator
Friend Shared Function AddMethodTo(destination As NamespaceBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As NamespaceBlockSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As CompilationUnitSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices,
after:=AddressOf LastMethod)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Shared Function AddMethodTo(destination As TypeBlockSyntax,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options)
Dim members = Insert(destination.Members, methodDeclaration, options, availableIndices,
after:=AddressOf LastMethod)
Return FixTerminators(destination.WithMembers(members))
End Function
Public Shared Function GenerateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)(method, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GenerateMethodDeclarationWorker(method, destination, options)
Return AddAnnotationsTo(method,
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, method, options)))
End Function
Private Shared Function GenerateMethodDeclarationWorker(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim isSub = method.ReturnType.SpecialType = SpecialType.System_Void
Dim kind = If(isSub, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement)
Dim keyword = If(isSub, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword)
Dim asClauseOpt = GenerateAsClause(method, isSub, options)
Dim implementsClauseOpt = GenerateImplementsClause(method.ExplicitInterfaceImplementations.FirstOrDefault())
Dim handlesClauseOpt = GenerateHandlesClause(CodeGenerationMethodInfo.GetHandlesExpressions(method))
Dim begin =
SyntaxFactory.MethodStatement(kind, subOrFunctionKeyword:=SyntaxFactory.Token(keyword), identifier:=method.Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks(method.GetAttributes(), options)).
WithModifiers(GenerateModifiers(method, destination, options)).
WithTypeParameterList(GenerateTypeParameterList(method)).
WithParameterList(ParameterGenerator.GenerateParameterList(method.Parameters, options)).
WithAsClause(asClauseOpt).
WithImplementsClause(implementsClauseOpt).
WithHandlesClause(handlesClauseOpt)
Dim hasNoBody = Not options.GenerateMethodBodies OrElse
method.IsAbstract OrElse
destination = CodeGenerationDestination.InterfaceType
If hasNoBody Then
Return begin
End If
Dim endConstruct = If(isSub, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement())
Return SyntaxFactory.MethodBlock(
If(isSub, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
begin,
statements:=StatementGenerator.GenerateStatements(method),
endSubOrFunctionStatement:=endConstruct)
End Function
Private Shared Function GenerateAsClause(method As IMethodSymbol, isSub As Boolean, options As CodeGenerationOptions) As SimpleAsClauseSyntax
If isSub Then
Return Nothing
End If
Return SyntaxFactory.SimpleAsClause(
AttributeGenerator.GenerateAttributeBlocks(method.GetReturnTypeAttributes(), options),
method.ReturnType.GenerateTypeSyntax())
End Function
Private Shared Function GenerateHandlesClause(expressions As IList(Of SyntaxNode)) As HandlesClauseSyntax
Dim memberAccessExpressions = expressions.OfType(Of MemberAccessExpressionSyntax).ToList()
Dim items = From def In memberAccessExpressions
Let expr1 = def.Expression
Where expr1 IsNot Nothing
Let expr2 = If(TypeOf expr1 Is ParenthesizedExpressionSyntax, DirectCast(expr1, ParenthesizedExpressionSyntax).Expression, expr1)
Let children = expr2.ChildNodesAndTokens()
Where children.Count = 1 AndAlso children(0).IsToken
Let token = children(0).AsToken()
Where token.Kind = SyntaxKind.IdentifierToken OrElse
token.Kind = SyntaxKind.MyBaseKeyword OrElse
token.Kind = SyntaxKind.MyClassKeyword OrElse
token.Kind = SyntaxKind.MeKeyword
Where TypeOf def.Name Is IdentifierNameSyntax
Let identifier = def.Name.Identifier.ValueText.ToIdentifierName()
Select SyntaxFactory.HandlesClauseItem(If(token.Kind = SyntaxKind.IdentifierToken,
DirectCast(SyntaxFactory.WithEventsEventContainer(token.ValueText.ToIdentifierToken()), EventContainerSyntax),
SyntaxFactory.KeywordEventContainer(token)), identifier)
Dim array = items.ToArray()
Return If(array.Length = 0, Nothing, SyntaxFactory.HandlesClause(array))
End Function
Private Overloads Shared Function GenerateTypeParameterList(method As IMethodSymbol) As TypeParameterListSyntax
Return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters)
End Function
Private Shared Function GenerateModifiers(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
Dim result As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(result)
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers(method.DeclaredAccessibility, result, destination, options, Accessibility.Public)
If method.IsAbstract Then
result.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If method.IsSealed Then
result.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
If method.IsVirtual Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If method.IsOverride Then
result.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If method.IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
result.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationMethodInfo.GetIsNew(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If CodeGenerationMethodInfo.GetIsAsyncMethod(method) Then
result.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
End If
End If
Return SyntaxFactory.TokenList(result)
End Using
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/PropertyGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module PropertyGenerator
Private Function LastPropertyOrField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration)) As TDeclaration
Dim lastProperty = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.PropertyBlock OrElse m.Kind = SyntaxKind.PropertyStatement)
Return If(lastProperty, LastField(members))
End Function
Friend Function AddPropertyTo(destination As CompilationUnitSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Function AddPropertyTo(destination As TypeBlockSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], GetDestination(destination), options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GeneratePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)([property], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Dim declaration = GeneratePropertyDeclarationWorker([property], destination, options)
Return AddAnnotationsTo([property],
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, [property], options)))
End Function
Private Function GeneratePropertyDeclarationWorker([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim implementsClauseOpt = GenerateImplementsClause([property].ExplicitInterfaceImplementations.FirstOrDefault())
Dim parameterList = GeneratePropertyParameterList([property], options)
Dim asClause = GenerateAsClause([property], options)
Dim begin = SyntaxFactory.PropertyStatement(identifier:=[property].Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks([property].GetAttributes(), options)).
WithModifiers(GenerateModifiers([property], destination, options, parameterList)).
WithParameterList(parameterList).
WithAsClause(asClause).
WithImplementsClause(implementsClauseOpt)
' If it's abstract or an auto-prop without a backing field, then we make just a single
' statement.
Dim getMethod = [property].GetMethod
Dim setMethod = [property].SetMethod
Dim hasStatements =
(getMethod IsNot Nothing AndAlso Not getMethod.IsAbstract) OrElse
(setMethod IsNot Nothing AndAlso Not setMethod.IsAbstract)
Dim hasNoBody =
Not options.GenerateMethodBodies OrElse
destination = CodeGenerationDestination.InterfaceType OrElse
[property].IsAbstract OrElse
Not hasStatements
If hasNoBody Then
Return begin
End If
Return SyntaxFactory.PropertyBlock(
begin,
accessors:=GenerateAccessorList([property], destination, options),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End Function
Private Function GeneratePropertyParameterList([property] As IPropertySymbol, options As CodeGenerationOptions) As ParameterListSyntax
If [property].Parameters.IsDefault OrElse [property].Parameters.Length = 0 Then
Return Nothing
End If
Return ParameterGenerator.GenerateParameterList([property].Parameters, options)
End Function
Private Function GenerateAccessorList([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxList(Of AccessorBlockSyntax)
Dim accessors = New List(Of AccessorBlockSyntax) From {
GenerateAccessor([property], [property].GetMethod, isGetter:=True, destination:=destination, options:=options),
GenerateAccessor([property], [property].SetMethod, isGetter:=False, destination:=destination, options:=options)
}
Return SyntaxFactory.List(accessors.WhereNotNull())
End Function
Private Function GenerateAccessor([property] As IPropertySymbol,
accessor As IMethodSymbol,
isGetter As Boolean,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As AccessorBlockSyntax
If accessor Is Nothing Then
Return Nothing
End If
Dim statementKind = If(isGetter, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement)
Dim blockKind = If(isGetter, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock)
If isGetter Then
Return SyntaxFactory.GetAccessorBlock(
SyntaxFactory.GetAccessorStatement().WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndGetStatement())
Else
Return SyntaxFactory.SetAccessorBlock(
SyntaxFactory.SetAccessorStatement() _
.WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)) _
.WithParameterList(SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Parameter(identifier:=SyntaxFactory.ModifiedIdentifier("value")).WithAsClause(SyntaxFactory.SimpleAsClause(type:=[property].Type.GenerateTypeSyntax()))))),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndSetStatement())
End If
End Function
Private Function GenerateAccessorStatements(accessor As IMethodSymbol) As SyntaxList(Of StatementSyntax)
Dim statementsOpt = CodeGenerationMethodInfo.GetStatements(accessor)
If Not statementsOpt.IsDefault Then
Return SyntaxFactory.List(statementsOpt.OfType(Of StatementSyntax))
Else
Return Nothing
End If
End Function
Private Function GenerateAccessorModifiers([property] As IPropertySymbol,
accessor As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
If accessor.DeclaredAccessibility = Accessibility.NotApplicable OrElse
accessor.DeclaredAccessibility = [property].DeclaredAccessibility Then
Return New SyntaxTokenList()
End If
Dim modifiers As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(modifiers)
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, destination, options, Accessibility.Public)
Return SyntaxFactory.TokenList(modifiers)
End Using
End Function
Private Function GenerateModifiers(
[property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
parameterList As ParameterListSyntax) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If [property].IsIndexer Then
Dim hasRequiredParameter = parameterList IsNot Nothing AndAlso parameterList.Parameters.Any(AddressOf IsRequired)
If hasRequiredParameter Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword))
End If
End If
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([property].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [property].IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationPropertyInfo.GetIsNew([property]) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If [property].IsVirtual Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If [property].IsOverride Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If [property].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If [property].IsSealed Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
End If
If [property].GetMethod Is Nothing AndAlso
[property].SetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword))
End If
If [property].SetMethod Is Nothing AndAlso
[property].GetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function IsRequired(parameter As ParameterSyntax) As Boolean
Return parameter.Modifiers.Count = 0 OrElse
parameter.Modifiers.Any(SyntaxKind.ByValKeyword) OrElse
parameter.Modifiers.Any(SyntaxKind.ByRefKeyword)
End Function
Private Function GenerateAsClause([property] As IPropertySymbol, options As CodeGenerationOptions) As AsClauseSyntax
Dim attributes = If([property].GetMethod IsNot Nothing,
AttributeGenerator.GenerateAttributeBlocks([property].GetMethod.GetReturnTypeAttributes(), options),
Nothing)
Return SyntaxFactory.SimpleAsClause(attributes, [property].Type.GenerateTypeSyntax())
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module PropertyGenerator
Private Function LastPropertyOrField(Of TDeclaration As SyntaxNode)(
members As SyntaxList(Of TDeclaration)) As TDeclaration
Dim lastProperty = members.LastOrDefault(Function(m) m.Kind = SyntaxKind.PropertyBlock OrElse m.Kind = SyntaxKind.PropertyStatement)
Return If(lastProperty, LastField(members))
End Function
Friend Function AddPropertyTo(destination As CompilationUnitSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], CodeGenerationDestination.CompilationUnit, options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
Return destination.WithMembers(SyntaxFactory.List(members))
End Function
Friend Function AddPropertyTo(destination As TypeBlockSyntax,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim propertyDeclaration = GeneratePropertyDeclaration([property], GetDestination(destination), options)
Dim members = Insert(destination.Members, propertyDeclaration, options, availableIndices,
after:=AddressOf LastPropertyOrField, before:=AddressOf FirstMember)
' Find the best place to put the field. It should go after the last field if we already
' have fields, or at the beginning of the file if we don't.
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function GeneratePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of DeclarationStatementSyntax)([property], options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax.GetDeclarationBlockFromBegin()
End If
Dim declaration = GeneratePropertyDeclarationWorker([property], destination, options)
Return AddAnnotationsTo([property],
AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(declaration, [property], options)))
End Function
Private Function GeneratePropertyDeclarationWorker([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As StatementSyntax
Dim implementsClauseOpt = GenerateImplementsClause([property].ExplicitInterfaceImplementations.FirstOrDefault())
Dim parameterList = GeneratePropertyParameterList([property], options)
Dim asClause = GenerateAsClause([property], options)
Dim begin = SyntaxFactory.PropertyStatement(identifier:=[property].Name.ToIdentifierToken).
WithAttributeLists(AttributeGenerator.GenerateAttributeBlocks([property].GetAttributes(), options)).
WithModifiers(GenerateModifiers([property], destination, options, parameterList)).
WithParameterList(parameterList).
WithAsClause(asClause).
WithImplementsClause(implementsClauseOpt)
' If it's abstract or an auto-prop without a backing field, then we make just a single
' statement.
Dim getMethod = [property].GetMethod
Dim setMethod = [property].SetMethod
Dim hasStatements =
(getMethod IsNot Nothing AndAlso Not getMethod.IsAbstract) OrElse
(setMethod IsNot Nothing AndAlso Not setMethod.IsAbstract)
Dim hasNoBody =
Not options.GenerateMethodBodies OrElse
destination = CodeGenerationDestination.InterfaceType OrElse
[property].IsAbstract OrElse
Not hasStatements
If hasNoBody Then
Return begin
End If
Return SyntaxFactory.PropertyBlock(
begin,
accessors:=GenerateAccessorList([property], destination, options),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End Function
Private Function GeneratePropertyParameterList([property] As IPropertySymbol, options As CodeGenerationOptions) As ParameterListSyntax
If [property].Parameters.IsDefault OrElse [property].Parameters.Length = 0 Then
Return Nothing
End If
Return ParameterGenerator.GenerateParameterList([property].Parameters, options)
End Function
Private Function GenerateAccessorList([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxList(Of AccessorBlockSyntax)
Dim accessors = New List(Of AccessorBlockSyntax) From {
GenerateAccessor([property], [property].GetMethod, isGetter:=True, destination:=destination, options:=options),
GenerateAccessor([property], [property].SetMethod, isGetter:=False, destination:=destination, options:=options)
}
Return SyntaxFactory.List(accessors.WhereNotNull())
End Function
Private Function GenerateAccessor([property] As IPropertySymbol,
accessor As IMethodSymbol,
isGetter As Boolean,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As AccessorBlockSyntax
If accessor Is Nothing Then
Return Nothing
End If
Dim statementKind = If(isGetter, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement)
Dim blockKind = If(isGetter, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock)
If isGetter Then
Return SyntaxFactory.GetAccessorBlock(
SyntaxFactory.GetAccessorStatement().WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndGetStatement())
Else
Return SyntaxFactory.SetAccessorBlock(
SyntaxFactory.SetAccessorStatement() _
.WithModifiers(GenerateAccessorModifiers([property], accessor, destination, options)) _
.WithParameterList(SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Parameter(identifier:=SyntaxFactory.ModifiedIdentifier("value")).WithAsClause(SyntaxFactory.SimpleAsClause(type:=[property].Type.GenerateTypeSyntax()))))),
GenerateAccessorStatements(accessor),
SyntaxFactory.EndSetStatement())
End If
End Function
Private Function GenerateAccessorStatements(accessor As IMethodSymbol) As SyntaxList(Of StatementSyntax)
Dim statementsOpt = CodeGenerationMethodInfo.GetStatements(accessor)
If Not statementsOpt.IsDefault Then
Return SyntaxFactory.List(statementsOpt.OfType(Of StatementSyntax))
Else
Return Nothing
End If
End Function
Private Function GenerateAccessorModifiers([property] As IPropertySymbol,
accessor As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxTokenList
If accessor.DeclaredAccessibility = Accessibility.NotApplicable OrElse
accessor.DeclaredAccessibility = [property].DeclaredAccessibility Then
Return New SyntaxTokenList()
End If
Dim modifiers As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(modifiers)
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, destination, options, Accessibility.Public)
Return SyntaxFactory.TokenList(modifiers)
End Using
End Function
Private Function GenerateModifiers(
[property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
parameterList As ParameterListSyntax) As SyntaxTokenList
Dim tokens As ArrayBuilder(Of SyntaxToken) = Nothing
Using x = ArrayBuilder(Of SyntaxToken).GetInstance(tokens)
If [property].IsIndexer Then
Dim hasRequiredParameter = parameterList IsNot Nothing AndAlso parameterList.Parameters.Any(AddressOf IsRequired)
If hasRequiredParameter Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword))
End If
End If
If destination <> CodeGenerationDestination.InterfaceType Then
AddAccessibilityModifiers([property].DeclaredAccessibility, tokens, destination, options, Accessibility.Public)
If [property].IsStatic AndAlso destination <> CodeGenerationDestination.ModuleType Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If CodeGenerationPropertyInfo.GetIsNew([property]) Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If [property].IsVirtual Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If [property].IsOverride Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If [property].IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
If [property].IsSealed Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
End If
If [property].GetMethod Is Nothing AndAlso
[property].SetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword))
End If
If [property].SetMethod Is Nothing AndAlso
[property].GetMethod IsNot Nothing Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
Return SyntaxFactory.TokenList(tokens)
End Using
End Function
Private Function IsRequired(parameter As ParameterSyntax) As Boolean
Return parameter.Modifiers.Count = 0 OrElse
parameter.Modifiers.Any(SyntaxKind.ByValKeyword) OrElse
parameter.Modifiers.Any(SyntaxKind.ByRefKeyword)
End Function
Private Function GenerateAsClause([property] As IPropertySymbol, options As CodeGenerationOptions) As AsClauseSyntax
Dim attributes = If([property].GetMethod IsNot Nothing,
AttributeGenerator.GenerateAttributeBlocks([property].GetMethod.GetReturnTypeAttributes(), options),
Nothing)
Return SyntaxFactory.SimpleAsClause(attributes, [property].Type.GenerateTypeSyntax())
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Core/Portable/Symbols/ITypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a type.
/// </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 ITypeSymbol : INamespaceOrTypeSymbol
{
/// <summary>
/// An enumerated value that identifies whether this type is an array, pointer, enum, and so on.
/// </summary>
TypeKind TypeKind { get; }
/// <summary>
/// The declared base type of this type, or null. The object type, interface types,
/// and pointer types do not have a base type. The base type of a type parameter
/// is its effective base class.
/// </summary>
INamedTypeSymbol? BaseType { get; }
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces. This does
/// include the interfaces declared as constraints on type parameters.
/// </summary>
ImmutableArray<INamedTypeSymbol> Interfaces { get; }
/// <summary>
/// The list of all interfaces of which this type is a declared subtype, excluding this type
/// itself. This includes all declared base interfaces, all declared base interfaces of base
/// types, and all declared base interfaces of those results (recursively). This also is the effective
/// interface set of a type parameter. Each result
/// appears exactly once in the list. This list is topologically sorted by the inheritance
/// relationship: if interface type A extends interface type B, then A precedes B in the
/// list. This is not quite the same as "all interfaces of which this type is a proper
/// subtype" because it does not take into account variance: AllInterfaces for
/// IEnumerable<string> will not include IEnumerable<object>.
/// </summary>
ImmutableArray<INamedTypeSymbol> AllInterfaces { get; }
/// <summary>
/// True if this type is known to be a reference type. It is never the case that
/// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type
/// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false.
/// </summary>
bool IsReferenceType { get; }
/// <summary>
/// True if this type is known to be a value type. It is never the case that
/// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type
/// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false.
/// </summary>
bool IsValueType { get; }
/// <summary>
/// Is this a symbol for an anonymous type (including anonymous VB delegate).
/// </summary>
bool IsAnonymousType { get; }
/// <summary>
/// Is this a symbol for a tuple .
/// </summary>
bool IsTupleType { get; }
/// <summary>
/// True if the type represents a native integer. In C#, the types represented
/// by language keywords 'nint' and 'nuint'.
/// </summary>
bool IsNativeIntegerType { get; }
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then <see cref="OriginalDefinition"/> gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
new ITypeSymbol OriginalDefinition { get; }
/// <summary>
/// An enumerated value that identifies certain 'special' types such as <see cref="System.Object"/>.
/// Returns <see cref="Microsoft.CodeAnalysis.SpecialType.None"/> if the type is not special.
/// </summary>
SpecialType SpecialType { get; }
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
/// <param name="interfaceMember">
/// Must be a non-null interface property, method, or event.
/// </param>
ISymbol? FindImplementationForInterfaceMember(ISymbol interfaceMember);
/// <summary>
/// True if the type is ref-like, meaning it follows rules similar to CLR by-ref variables. False if the type
/// is not ref-like or if the language has no concept of ref-like types.
/// </summary>
/// <remarks>
/// <see cref="Span{T}" /> is a commonly used ref-like type.
/// </remarks>
bool IsRefLikeType { get; }
/// <summary>
/// True if the type is unmanaged according to language rules. False if managed or if the language
/// has no concept of unmanaged types.
/// </summary>
bool IsUnmanagedType { get; }
/// <summary>
/// True if the type is readonly.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// True if the type is a record.
/// </summary>
bool IsRecord { get; }
/// <summary>
/// Converts an <c>ITypeSymbol</c> and a nullable flow state to a string representation.
/// </summary>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="format">Format or null for the default.</param>
/// <returns>A formatted string representation of the symbol with the given nullability.</returns>
string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null);
/// <summary>
/// Converts a symbol to an array of string parts, each of which has a kind. Useful
/// for colorizing the display string.
/// </summary>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="format">Format or null for the default.</param>
/// <returns>A read-only array of string parts.</returns>
ImmutableArray<SymbolDisplayPart> ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null);
/// <summary>
/// Converts a symbol to a string that can be displayed to the user. May be tailored to a
/// specific location in the source code.
/// </summary>
/// <param name="semanticModel">Binding information (for determining names appropriate to
/// the context).</param>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="position">A position in the source code (context).</param>
/// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param>
/// <returns>A formatted string that can be displayed to the user.</returns>
string ToMinimalDisplayString(
SemanticModel semanticModel,
NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat? format = null);
/// <summary>
/// Convert a symbol to an array of string parts, each of which has a kind. May be tailored
/// to a specific location in the source code. Useful for colorizing the display string.
/// </summary>
/// <param name="semanticModel">Binding information (for determining names appropriate to
/// the context).</param>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="position">A position in the source code (context).</param>
/// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param>
/// <returns>A read-only array of string parts.</returns>
ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat? format = null);
/// <summary>
/// Nullable annotation associated with the type, or <see cref="NullableAnnotation.None"/> if there are none.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns the same type as this type but with the given nullable annotation.
/// </summary>
/// <param name="nullableAnnotation">The nullable annotation to use</param>
ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation);
}
// Intentionally not extension methods. We don't want them ever be called for symbol classes
// Once Default Interface Implementations are supported, we can move these methods into the interface.
internal static class ITypeSymbolHelpers
{
internal static bool IsNullableType([NotNullWhen(returnValue: true)] ITypeSymbol? typeOpt)
{
return typeOpt?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
internal static bool IsNullableOfBoolean([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return IsNullableType(type) && IsBooleanType(GetNullableUnderlyingType(type));
}
internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type)
{
Debug.Assert(IsNullableType(type));
return ((INamedTypeSymbol)type).TypeArguments[0];
}
internal static bool IsBooleanType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType == SpecialType.System_Boolean;
}
internal static bool IsObjectType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType == SpecialType.System_Object;
}
internal static bool IsSignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsSignedIntegralType() == true;
}
internal static bool IsUnsignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsUnsignedIntegralType() == true;
}
internal static bool IsNumericType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsNumericType() == true;
}
internal static ITypeSymbol? GetEnumUnderlyingType(ITypeSymbol? type)
{
return (type as INamedTypeSymbol)?.EnumUnderlyingType;
}
[return: NotNullIfNotNull(parameterName: "type")]
internal static ITypeSymbol? GetEnumUnderlyingTypeOrSelf(ITypeSymbol? type)
{
return GetEnumUnderlyingType(type) ?? type;
}
internal static bool IsDynamicType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.Kind == SymbolKind.DynamicType;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a type.
/// </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 ITypeSymbol : INamespaceOrTypeSymbol
{
/// <summary>
/// An enumerated value that identifies whether this type is an array, pointer, enum, and so on.
/// </summary>
TypeKind TypeKind { get; }
/// <summary>
/// The declared base type of this type, or null. The object type, interface types,
/// and pointer types do not have a base type. The base type of a type parameter
/// is its effective base class.
/// </summary>
INamedTypeSymbol? BaseType { get; }
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces. This does
/// include the interfaces declared as constraints on type parameters.
/// </summary>
ImmutableArray<INamedTypeSymbol> Interfaces { get; }
/// <summary>
/// The list of all interfaces of which this type is a declared subtype, excluding this type
/// itself. This includes all declared base interfaces, all declared base interfaces of base
/// types, and all declared base interfaces of those results (recursively). This also is the effective
/// interface set of a type parameter. Each result
/// appears exactly once in the list. This list is topologically sorted by the inheritance
/// relationship: if interface type A extends interface type B, then A precedes B in the
/// list. This is not quite the same as "all interfaces of which this type is a proper
/// subtype" because it does not take into account variance: AllInterfaces for
/// IEnumerable<string> will not include IEnumerable<object>.
/// </summary>
ImmutableArray<INamedTypeSymbol> AllInterfaces { get; }
/// <summary>
/// True if this type is known to be a reference type. It is never the case that
/// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type
/// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false.
/// </summary>
bool IsReferenceType { get; }
/// <summary>
/// True if this type is known to be a value type. It is never the case that
/// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type
/// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false.
/// </summary>
bool IsValueType { get; }
/// <summary>
/// Is this a symbol for an anonymous type (including anonymous VB delegate).
/// </summary>
bool IsAnonymousType { get; }
/// <summary>
/// Is this a symbol for a tuple .
/// </summary>
bool IsTupleType { get; }
/// <summary>
/// True if the type represents a native integer. In C#, the types represented
/// by language keywords 'nint' and 'nuint'.
/// </summary>
bool IsNativeIntegerType { get; }
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then <see cref="OriginalDefinition"/> gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
new ITypeSymbol OriginalDefinition { get; }
/// <summary>
/// An enumerated value that identifies certain 'special' types such as <see cref="System.Object"/>.
/// Returns <see cref="Microsoft.CodeAnalysis.SpecialType.None"/> if the type is not special.
/// </summary>
SpecialType SpecialType { get; }
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
/// <param name="interfaceMember">
/// Must be a non-null interface property, method, or event.
/// </param>
ISymbol? FindImplementationForInterfaceMember(ISymbol interfaceMember);
/// <summary>
/// True if the type is ref-like, meaning it follows rules similar to CLR by-ref variables. False if the type
/// is not ref-like or if the language has no concept of ref-like types.
/// </summary>
/// <remarks>
/// <see cref="Span{T}" /> is a commonly used ref-like type.
/// </remarks>
bool IsRefLikeType { get; }
/// <summary>
/// True if the type is unmanaged according to language rules. False if managed or if the language
/// has no concept of unmanaged types.
/// </summary>
bool IsUnmanagedType { get; }
/// <summary>
/// True if the type is readonly.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// True if the type is a record.
/// </summary>
bool IsRecord { get; }
/// <summary>
/// Converts an <c>ITypeSymbol</c> and a nullable flow state to a string representation.
/// </summary>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="format">Format or null for the default.</param>
/// <returns>A formatted string representation of the symbol with the given nullability.</returns>
string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null);
/// <summary>
/// Converts a symbol to an array of string parts, each of which has a kind. Useful
/// for colorizing the display string.
/// </summary>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="format">Format or null for the default.</param>
/// <returns>A read-only array of string parts.</returns>
ImmutableArray<SymbolDisplayPart> ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null);
/// <summary>
/// Converts a symbol to a string that can be displayed to the user. May be tailored to a
/// specific location in the source code.
/// </summary>
/// <param name="semanticModel">Binding information (for determining names appropriate to
/// the context).</param>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="position">A position in the source code (context).</param>
/// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param>
/// <returns>A formatted string that can be displayed to the user.</returns>
string ToMinimalDisplayString(
SemanticModel semanticModel,
NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat? format = null);
/// <summary>
/// Convert a symbol to an array of string parts, each of which has a kind. May be tailored
/// to a specific location in the source code. Useful for colorizing the display string.
/// </summary>
/// <param name="semanticModel">Binding information (for determining names appropriate to
/// the context).</param>
/// <param name="topLevelNullability">The top-level nullability to use for formatting.</param>
/// <param name="position">A position in the source code (context).</param>
/// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param>
/// <returns>A read-only array of string parts.</returns>
ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat? format = null);
/// <summary>
/// Nullable annotation associated with the type, or <see cref="NullableAnnotation.None"/> if there are none.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns the same type as this type but with the given nullable annotation.
/// </summary>
/// <param name="nullableAnnotation">The nullable annotation to use</param>
ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation);
}
// Intentionally not extension methods. We don't want them ever be called for symbol classes
// Once Default Interface Implementations are supported, we can move these methods into the interface.
internal static class ITypeSymbolHelpers
{
internal static bool IsNullableType([NotNullWhen(returnValue: true)] ITypeSymbol? typeOpt)
{
return typeOpt?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
internal static bool IsNullableOfBoolean([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return IsNullableType(type) && IsBooleanType(GetNullableUnderlyingType(type));
}
internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type)
{
Debug.Assert(IsNullableType(type));
return ((INamedTypeSymbol)type).TypeArguments[0];
}
internal static bool IsBooleanType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType == SpecialType.System_Boolean;
}
internal static bool IsObjectType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType == SpecialType.System_Object;
}
internal static bool IsSignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsSignedIntegralType() == true;
}
internal static bool IsUnsignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsUnsignedIntegralType() == true;
}
internal static bool IsNumericType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.SpecialType.IsNumericType() == true;
}
internal static ITypeSymbol? GetEnumUnderlyingType(ITypeSymbol? type)
{
return (type as INamedTypeSymbol)?.EnumUnderlyingType;
}
[return: NotNullIfNotNull(parameterName: "type")]
internal static ITypeSymbol? GetEnumUnderlyingTypeOrSelf(ITypeSymbol? type)
{
return GetEnumUnderlyingType(type) ?? type;
}
internal static bool IsDynamicType([NotNullWhen(returnValue: true)] ITypeSymbol? type)
{
return type?.Kind == SymbolKind.DynamicType;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Test/Core/Compilation/RuntimeUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>
/// Hide all of the runtime specific implementations of types that we need to use when multi-targeting.
/// </summary>
public static partial class RuntimeUtilities
{
internal static bool IsDesktopRuntime =>
#if NET472
true;
#elif NETCOREAPP
false;
#elif NETSTANDARD2_0
throw new PlatformNotSupportedException();
#else
#error Unsupported configuration
#endif
internal static bool IsCoreClrRuntime => !IsDesktopRuntime;
internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null, string tempDirectory = null)
{
tempDirectory = tempDirectory ?? Path.GetTempPath();
#if NET472
return new BuildPaths(
clientDir: Path.GetDirectoryName(typeof(BuildPathsUtil).Assembly.Location),
workingDir: workingDirectory,
sdkDir: sdkDirectory ?? RuntimeEnvironment.GetRuntimeDirectory(),
tempDir: tempDirectory);
#else
return new BuildPaths(
clientDir: AppContext.BaseDirectory,
workingDir: workingDirectory,
sdkDir: sdkDirectory,
tempDir: tempDirectory);
#endif
}
internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory()
{
#if NET472
return new Roslyn.Test.Utilities.Desktop.DesktopRuntimeEnvironmentFactory();
#elif NETCOREAPP
return new Roslyn.Test.Utilities.CoreClr.CoreCLRRuntimeEnvironmentFactory();
#elif NETSTANDARD2_0
throw new PlatformNotSupportedException();
#else
#error Unsupported configuration
#endif
}
/// <summary>
/// Get the location of the assembly that contains this type
/// </summary>
internal static string GetAssemblyLocation(Type type)
{
return type.GetTypeInfo().Assembly.Location;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
/// <summary>
/// Hide all of the runtime specific implementations of types that we need to use when multi-targeting.
/// </summary>
public static partial class RuntimeUtilities
{
internal static bool IsDesktopRuntime =>
#if NET472
true;
#elif NETCOREAPP
false;
#elif NETSTANDARD2_0
throw new PlatformNotSupportedException();
#else
#error Unsupported configuration
#endif
internal static bool IsCoreClrRuntime => !IsDesktopRuntime;
internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null, string tempDirectory = null)
{
tempDirectory = tempDirectory ?? Path.GetTempPath();
#if NET472
return new BuildPaths(
clientDir: Path.GetDirectoryName(typeof(BuildPathsUtil).Assembly.Location),
workingDir: workingDirectory,
sdkDir: sdkDirectory ?? RuntimeEnvironment.GetRuntimeDirectory(),
tempDir: tempDirectory);
#else
return new BuildPaths(
clientDir: AppContext.BaseDirectory,
workingDir: workingDirectory,
sdkDir: sdkDirectory,
tempDir: tempDirectory);
#endif
}
internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory()
{
#if NET472
return new Roslyn.Test.Utilities.Desktop.DesktopRuntimeEnvironmentFactory();
#elif NETCOREAPP
return new Roslyn.Test.Utilities.CoreClr.CoreCLRRuntimeEnvironmentFactory();
#elif NETSTANDARD2_0
throw new PlatformNotSupportedException();
#else
#error Unsupported configuration
#endif
}
/// <summary>
/// Get the location of the assembly that contains this type
/// </summary>
internal static string GetAssemblyLocation(Type type)
{
return type.GetTypeInfo().Assembly.Location;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/KeywordCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources
{
public class KeywordCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(KeywordCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task IsCommitCharacterTest()
=> await VerifyCommonCommitCharactersAsync("$$", textTypedSoFar: "");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void IsTextualTriggerCharacterTest()
=> TestCommonIsTextualTriggerCharacter();
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task SendEnterThroughToEditorTest()
{
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InEmptyFile()
{
var markup = "$$";
await VerifyAnyItemExistsAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInInactiveCode()
{
var markup = @"class C
{
void M()
{
#if false
$$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInCharLiteral()
{
var markup = @"class C
{
void M()
{
var c = '$$';
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedCharLiteral()
{
var markup = @"class C
{
void M()
{
var c = '$$ ";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedCharLiteralAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var c = '$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInString()
{
var markup = @"class C
{
void M()
{
var s = ""$$"";
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInStringInDirective()
{
var markup = "#r \"$$\"";
await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedString()
{
var markup = @"class C
{
void M()
{
var s = ""$$ ";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedStringInDirective()
{
var markup = "#r \"$$\"";
await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedStringAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var s = ""$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInVerbatimString()
{
var markup = @"class C
{
void M()
{
var s = @""
$$
"";
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedVerbatimString()
{
var markup = @"class C
{
void M()
{
var s = @""
$$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedVerbatimStringAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var s = @""$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInSingleLineComment()
{
var markup = @"class C
{
void M()
{
// $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInSingleLineCommentAtEndOfFile()
{
var markup = @"namespace A
{
}// $$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInMutliLineComment()
{
var markup = @"class C
{
void M()
{
/*
$$
*/
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
void goo() {
#endif
$$
#if GOO
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "public", null);
await VerifyItemInLinkedFilesAsync(markup, "for", null);
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_AfterGetAccessorInSingleLineIncompleteProperty()
{
var markupBeforeCommit = @"class Program
{
int P {g$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
int P {get;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "get", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_AfterBothAccessorsInSingleLineIncompleteProperty()
{
var markupBeforeCommit = @"class Program
{
int P {get;set$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
int P {get;set;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "set", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_InSingleLineMethod()
{
var markupBeforeCommit = @"class Program
{
public static void Test() { return$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
public static void Test() { return;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "return", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(14218, "https://github.com/dotnet/roslyn/issues/14218")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PredefinedTypeKeywordsShouldBeRecommendedAfterCaseInASwitch()
{
var text = @"
class Program
{
public static void Test()
{
object o = null;
switch (o)
{
case $$
}
}
}";
await VerifyItemExistsAsync(text, "int");
await VerifyItemExistsAsync(text, "string");
await VerifyItemExistsAsync(text, "byte");
await VerifyItemExistsAsync(text, "char");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrivateOrProtectedModifiers()
{
var text = @"
class C
{
$$
}";
await VerifyItemExistsAsync(text, "private");
await VerifyItemExistsAsync(text, "protected");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrivateProtectedModifier()
{
var text = @"
class C
{
private $$
}";
await VerifyItemExistsAsync(text, "protected");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ProtectedPrivateModifier()
{
var text = @"
class C
{
protected $$
}";
await VerifyItemExistsAsync(text, "private");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task DontSuggestEventAfterReadonlyInClass()
{
var markup =
@"class C {
readonly $$
}
";
await VerifyItemIsAbsentAsync(markup, "event");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task DontSuggestEventAfterReadonlyInInterface()
{
var markup =
@"interface C {
readonly $$
}
";
await VerifyItemIsAbsentAsync(markup, "event");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task SuggestEventAfterReadonlyInStruct()
{
var markup =
@"struct C {
readonly $$
}
";
await VerifyItemExistsAsync(markup, "event");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("record struct", true)]
[InlineData("class", false)]
[InlineData("record", false)]
[InlineData("record class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyPropertyAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int X {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyBeforePropertyAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int X {{
$$ get;
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyIndexerAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int this[int i] {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyEventAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
event System.Action E {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
public async Task SuggestAccessorAfterReadonlyInStruct()
{
var markup =
@"struct C {
int X {
readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "get");
await VerifyItemExistsAsync(markup, "set");
await VerifyItemIsAbsentAsync(markup, "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
public async Task SuggestReadonlyMethodInStruct()
{
var markup =
@"struct C {
public $$ void M() {}
}
";
await VerifyItemExistsAsync(markup, "readonly");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources
{
public class KeywordCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(KeywordCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task IsCommitCharacterTest()
=> await VerifyCommonCommitCharactersAsync("$$", textTypedSoFar: "");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void IsTextualTriggerCharacterTest()
=> TestCommonIsTextualTriggerCharacter();
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task SendEnterThroughToEditorTest()
{
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "class", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InEmptyFile()
{
var markup = "$$";
await VerifyAnyItemExistsAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInInactiveCode()
{
var markup = @"class C
{
void M()
{
#if false
$$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInCharLiteral()
{
var markup = @"class C
{
void M()
{
var c = '$$';
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedCharLiteral()
{
var markup = @"class C
{
void M()
{
var c = '$$ ";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedCharLiteralAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var c = '$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInString()
{
var markup = @"class C
{
void M()
{
var s = ""$$"";
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInStringInDirective()
{
var markup = "#r \"$$\"";
await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedString()
{
var markup = @"class C
{
void M()
{
var s = ""$$ ";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedStringInDirective()
{
var markup = "#r \"$$\"";
await VerifyNoItemsExistAsync(markup, SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedStringAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var s = ""$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInVerbatimString()
{
var markup = @"class C
{
void M()
{
var s = @""
$$
"";
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedVerbatimString()
{
var markup = @"class C
{
void M()
{
var s = @""
$$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInUnterminatedVerbatimStringAtEndOfFile()
{
var markup = @"class C
{
void M()
{
var s = @""$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInSingleLineComment()
{
var markup = @"class C
{
void M()
{
// $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInSingleLineCommentAtEndOfFile()
{
var markup = @"namespace A
{
}// $$";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInMutliLineComment()
{
var markup = @"class C
{
void M()
{
/*
$$
*/
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
void goo() {
#endif
$$
#if GOO
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "public", null);
await VerifyItemInLinkedFilesAsync(markup, "for", null);
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_AfterGetAccessorInSingleLineIncompleteProperty()
{
var markupBeforeCommit = @"class Program
{
int P {g$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
int P {get;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "get", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_AfterBothAccessorsInSingleLineIncompleteProperty()
{
var markupBeforeCommit = @"class Program
{
int P {get;set$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
int P {get;set;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "set", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(7768, "https://github.com/dotnet/roslyn/issues/7768")]
[WorkItem(8228, "https://github.com/dotnet/roslyn/issues/8228")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FormattingAfterCompletionCommit_InSingleLineMethod()
{
var markupBeforeCommit = @"class Program
{
public static void Test() { return$$
void Main() { }
}";
var expectedCodeAfterCommit = @"class Program
{
public static void Test() { return;
void Main() { }
}";
await VerifyProviderCommitAsync(markupBeforeCommit, "return", expectedCodeAfterCommit, commitChar: ';');
}
[WorkItem(14218, "https://github.com/dotnet/roslyn/issues/14218")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PredefinedTypeKeywordsShouldBeRecommendedAfterCaseInASwitch()
{
var text = @"
class Program
{
public static void Test()
{
object o = null;
switch (o)
{
case $$
}
}
}";
await VerifyItemExistsAsync(text, "int");
await VerifyItemExistsAsync(text, "string");
await VerifyItemExistsAsync(text, "byte");
await VerifyItemExistsAsync(text, "char");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrivateOrProtectedModifiers()
{
var text = @"
class C
{
$$
}";
await VerifyItemExistsAsync(text, "private");
await VerifyItemExistsAsync(text, "protected");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrivateProtectedModifier()
{
var text = @"
class C
{
private $$
}";
await VerifyItemExistsAsync(text, "protected");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ProtectedPrivateModifier()
{
var text = @"
class C
{
protected $$
}";
await VerifyItemExistsAsync(text, "private");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task DontSuggestEventAfterReadonlyInClass()
{
var markup =
@"class C {
readonly $$
}
";
await VerifyItemIsAbsentAsync(markup, "event");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task DontSuggestEventAfterReadonlyInInterface()
{
var markup =
@"interface C {
readonly $$
}
";
await VerifyItemIsAbsentAsync(markup, "event");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(34774, "https://github.com/dotnet/roslyn/issues/34774")]
public async Task SuggestEventAfterReadonlyInStruct()
{
var markup =
@"struct C {
readonly $$
}
";
await VerifyItemExistsAsync(markup, "event");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("record struct", true)]
[InlineData("class", false)]
[InlineData("record", false)]
[InlineData("record class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyPropertyAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int X {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyBeforePropertyAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int X {{
$$ get;
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyIndexerAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
int this[int i] {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
[InlineData("struct", true)]
[InlineData("class", false)]
[InlineData("interface", false)]
public async Task SuggestReadonlyEventAccessor(string declarationType, bool present)
{
var markup =
$@"{declarationType} C {{
event System.Action E {{
$$
}}
}}
";
if (present)
{
await VerifyItemExistsAsync(markup, "readonly");
}
else
{
await VerifyItemIsAbsentAsync(markup, "readonly");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
public async Task SuggestAccessorAfterReadonlyInStruct()
{
var markup =
@"struct C {
int X {
readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "get");
await VerifyItemExistsAsync(markup, "set");
await VerifyItemIsAbsentAsync(markup, "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(39265, "https://github.com/dotnet/roslyn/issues/39265")]
public async Task SuggestReadonlyMethodInStruct()
{
var markup =
@"struct C {
public $$ void M() {}
}
";
await VerifyItemExistsAsync(markup, "readonly");
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerNodeSetup.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.ComponentModel.Design;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
[Export(typeof(IAnalyzerNodeSetup))]
internal sealed class AnalyzerNodeSetup : IAnalyzerNodeSetup
{
private readonly AnalyzerItemsTracker _analyzerTracker;
private readonly AnalyzersCommandHandler _analyzerCommandHandler;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerNodeSetup(AnalyzerItemsTracker analyzerTracker, AnalyzersCommandHandler analyzerCommandHandler)
{
_analyzerTracker = analyzerTracker;
_analyzerCommandHandler = analyzerCommandHandler;
}
public void Initialize(IServiceProvider serviceProvider)
{
_analyzerTracker.Register();
_analyzerCommandHandler.Initialize((IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService)));
}
public void Unregister()
{
_analyzerTracker.Unregister();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.ComponentModel.Design;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
[Export(typeof(IAnalyzerNodeSetup))]
internal sealed class AnalyzerNodeSetup : IAnalyzerNodeSetup
{
private readonly AnalyzerItemsTracker _analyzerTracker;
private readonly AnalyzersCommandHandler _analyzerCommandHandler;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerNodeSetup(AnalyzerItemsTracker analyzerTracker, AnalyzersCommandHandler analyzerCommandHandler)
{
_analyzerTracker = analyzerTracker;
_analyzerCommandHandler = analyzerCommandHandler;
}
public void Initialize(IServiceProvider serviceProvider)
{
_analyzerTracker.Register();
_analyzerCommandHandler.Initialize((IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService)));
}
public void Unregister()
{
_analyzerTracker.Unregister();
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_ElseIf_WithNext.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements
Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests
<Theory>
<InlineData("[||]if a then")>
<InlineData("i[||]f a then")>
<InlineData("if[||] a then")>
<InlineData("if a [||]then")>
<InlineData("if a th[||]en")>
<InlineData("if a then[||]")>
<InlineData("[|if|] a then")>
<InlineData("[|if a then|]")>
Public Async Function MergedOnIfSpans(ifLine As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedStatementSelection() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
|] elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()|]
elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
|] elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()|]
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
|] else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if|]
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if
|] end sub
end class")
End Function
<Theory>
<InlineData("if [||]a then")>
<InlineData("[|i|]f a then")>
<InlineData("[|if a|] then")>
<InlineData("if [|a|] then")>
<InlineData("if a [|then|]")>
Public Async Function NotMergedOnIfSpans(ifLine As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfOverreachingSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
|]elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfBodyStatementSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a then
[|return|]
elseif b then
return
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithNextOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithPreviousOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithBoth() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected1 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected2 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 2)
Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0)
Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1)
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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements
Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests
<Theory>
<InlineData("[||]if a then")>
<InlineData("i[||]f a then")>
<InlineData("if[||] a then")>
<InlineData("if a [||]then")>
<InlineData("if a th[||]en")>
<InlineData("if a then[||]")>
<InlineData("[|if|] a then")>
<InlineData("[|if a then|]")>
Public Async Function MergedOnIfSpans(ifLine As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedStatementSelection() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
|] elseif b then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()|]
elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnIfExtendedFullSelectionWithoutElseIfClause() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
|] elseif b then
System.Console.WriteLine()
else
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a OrElse b then
System.Console.WriteLine()
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()|]
else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfClause() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
|] else
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if|]
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfExtendedFullSelectionWithElseIfElseClauses() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[| if a then
System.Console.WriteLine()
elseif b then
System.Console.WriteLine()
else
end if
|] end sub
end class")
End Function
<Theory>
<InlineData("if [||]a then")>
<InlineData("[|i|]f a then")>
<InlineData("[|if a|] then")>
<InlineData("if [|a|] then")>
<InlineData("if a [|then|]")>
Public Async Function NotMergedOnIfSpans(ifLine As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
{ifLine}
elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfOverreachingSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[|if a then
|]elseif b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotMergedOnIfBodyStatementSelection() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a then
[|return|]
elseif b then
return
end if
end sub
end class")
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithNextOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine(nothing)
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithPreviousOnly() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Const Expected As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine(nothing)
end if
end sub
end class"
Await TestActionCountAsync(Initial, 1)
Await TestInRegularAndScriptAsync(Initial, Expected)
End Function
<Fact>
Public Async Function MergedOnMiddleIfMergableWithBoth() As Task
Const Initial As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
[||]elseif b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected1 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a OrElse b then
System.Console.WriteLine()
elseif c then
System.Console.WriteLine()
end if
end sub
end class"
Const Expected2 As String =
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
System.Console.WriteLine()
elseif b OrElse c then
System.Console.WriteLine()
end if
end sub
end class"
Await TestActionCountAsync(Initial, 2)
Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0)
Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncExceptionHandlerRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The purpose of this rewriter is to replace await-containing catch and finally handlers
/// with surrogate replacements that keep actual handler code in regular code blocks.
/// That allows these constructs to be further lowered at the async lowering pass.
/// </summary>
internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private readonly SyntheticBoundNodeFactory _F;
private readonly AwaitInFinallyAnalysis _analysis;
private AwaitCatchFrame _currentAwaitCatchFrame;
private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame();
private AsyncExceptionHandlerRewriter(
MethodSymbol containingMethod,
NamedTypeSymbol containingType,
SyntheticBoundNodeFactory factory,
AwaitInFinallyAnalysis analysis)
{
_F = factory;
_F.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_analysis = analysis;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// The goal is to not have exception handlers that contain awaits in them.
///
/// 1) Await containing finally blocks:
/// The general strategy is to rewrite await containing handlers into synthetic handlers.
/// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them.
/// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually
/// (this is the hard part of the rewrite).
///
/// try{
/// code;
/// }finally{
/// handler;
/// }
///
/// Into ===>
///
/// Exception ex = null;
/// int pendingBranch = 0;
///
/// try{
/// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel
/// goto finallyLabel;
/// }catch (ex){ // essentially pend the currently active exception
/// };
///
/// finallyLabel:
/// {
/// handler;
/// if (ex != null) throw ex; // unpend the exception
/// unpend branches/return
/// }
///
/// 2) Await containing catches:
/// try{
/// code;
/// }catch (Exception ex){
/// handler;
/// throw;
/// }
///
///
/// Into ===>
///
/// Object pendingException;
/// int pendingCatch = 0;
///
/// try{
/// code;
/// }catch (Exception temp){ // essentially pend the currently active exception
/// pendingException = temp;
/// pendingCatch = 1;
/// };
///
/// switch(pendingCatch):
/// {
/// case 1:
/// {
/// Exception ex = (Exception)pendingException;
/// handler;
/// throw pendingException
/// }
/// }
/// </summary>
public static BoundStatement Rewrite(
MethodSymbol containingSymbol,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(containingSymbol != null);
Debug.Assert((object)containingType != null);
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
var analysis = new AwaitInFinallyAnalysis(statement);
if (!analysis.ContainsAwaitInHandlers())
{
return statement;
}
var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics);
var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis);
var loweredStatement = (BoundStatement)rewriter.Visit(statement);
return loweredStatement;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var tryStatementSyntax = node.Syntax;
// If you add a syntax kind to the assertion below, please also ensure
// that the scenario has been tested with Edit-and-Continue.
Debug.Assert(
tryStatementSyntax.IsKind(SyntaxKind.TryStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LockStatement));
BoundStatement finalizedRegion;
BoundBlock rewrittenFinally;
var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node);
if (!finallyContainsAwaits)
{
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt);
if (rewrittenFinally == null)
{
return finalizedRegion;
}
var asTry = finalizedRegion as BoundTryStatement;
if (asTry != null)
{
// since finalized region is a try we can just attach finally to it
Debug.Assert(asTry.FinallyBlockOpt == null);
return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler);
}
else
{
// wrap finalizedRegion into a Try with a finally.
return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally);
}
}
// rewrite finalized region (try and catches) in the current frame
var frame = PushFrame(node);
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt);
PopFrame();
var exceptionType = _F.SpecialType(SpecialType.System_Object);
var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax);
var finallyLabel = _F.GenerateLabel("finallyLabel");
var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax);
var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block());
var catchAndPendException = _F.Try(
_F.Block(
finalizedRegion,
_F.HiddenSequencePoint(),
_F.Goto(finallyLabel),
PendBranches(frame, pendingBranchVar, finallyLabel)),
ImmutableArray.Create(catchAll),
finallyLabel: finallyLabel);
BoundBlock syntheticFinallyBlock = _F.Block(
_F.HiddenSequencePoint(),
_F.Label(finallyLabel),
rewrittenFinally,
_F.HiddenSequencePoint(),
UnpendException(pendingExceptionLocal),
UnpendBranches(
frame,
pendingBranchVar,
pendingExceptionLocal));
BoundStatement syntheticFinally = syntheticFinallyBlock;
if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator)
{
// We wrap this block so that it can be processed as a finally block by async-iterator rewriting
syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock);
}
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(_F.HiddenSequencePoint());
locals.Add(pendingExceptionLocal);
statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type)));
locals.Add(pendingBranchVar);
statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type)));
LocalSymbol returnLocal = frame.returnValue;
if (returnLocal != null)
{
locals.Add(returnLocal);
}
statements.Add(catchAndPendException);
statements.Add(syntheticFinally);
var completeTry = _F.Block(
locals.ToImmutableAndFree(),
statements.ToImmutableAndFree());
return completeTry;
}
private BoundBlock PendBranches(
AwaitFinallyFrame frame,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance();
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
var proxyLabels = frame.proxyLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var proxied = proxiedLabels[i - 1];
var proxy = proxyLabels[proxied];
PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel);
}
}
var returnProxy = frame.returnProxyLabel;
if (returnProxy != null)
{
PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel);
}
return _F.Block(bodyStatements.ToImmutableAndFree());
}
private void PendBranch(
ArrayBuilder<BoundStatement> bodyStatements,
LabelSymbol proxy,
int i,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
// branch lands here
bodyStatements.Add(_F.Label(proxy));
// pend the branch
bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i)));
// skip other proxies
bodyStatements.Add(_F.Goto(finallyLabel));
}
private BoundStatement UnpendBranches(
AwaitFinallyFrame frame,
SynthesizedLocal pendingBranchVar,
SynthesizedLocal pendingException)
{
var parent = frame.ParentOpt;
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance();
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var target = proxiedLabels[i - 1];
var parentProxy = parent.ProxyLabelIfNeeded(target);
var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy));
cases.Add(caseStatement);
}
}
if (frame.returnProxyLabel != null)
{
BoundLocal pendingValue = null;
if (frame.returnValue != null)
{
pendingValue = _F.Local(frame.returnValue);
}
SynthesizedLocal returnValue;
BoundStatement unpendReturn;
var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue);
if (returnLabel == null)
{
unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue);
}
else
{
if (pendingValue == null)
{
unpendReturn = _F.Goto(returnLabel);
}
else
{
unpendReturn = _F.Block(
_F.Assignment(
_F.Local(returnValue),
pendingValue),
_F.Goto(returnLabel));
}
}
var caseStatement = _F.SwitchSection(i, unpendReturn);
cases.Add(caseStatement);
}
return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree());
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt);
BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt);
var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label);
return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?");
return base.VisitConditionalGoto(node);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
SynthesizedLocal returnValue;
var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded(
_F.CurrentFunction,
node.ExpressionOpt,
out returnValue);
if (returnLabel == null)
{
return base.VisitReturnStatement(node);
}
var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt));
if (returnExpr != null)
{
return _F.Block(
_F.Assignment(
_F.Local(returnValue),
returnExpr),
_F.Goto(
returnLabel));
}
else
{
return _F.Goto(returnLabel);
}
}
private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal)
{
// create a temp.
// pendingExceptionLocal will certainly be captured, no need to access it over and over.
LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object));
var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal));
// throw pendingExceptionLocal;
BoundStatement rethrow = Rethrow(obj);
return _F.Block(
ImmutableArray.Create<LocalSymbol>(obj),
objInit,
_F.If(
_F.ObjectNotEqual(
_F.Local(obj),
_F.Null(obj.Type)),
rethrow));
}
private BoundStatement Rethrow(LocalSymbol obj)
{
// conservative rethrow
BoundStatement rethrow = _F.Throw(_F.Local(obj));
var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true);
var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true);
// if these helpers are available, we can rethrow with original stack info
// as long as it derives from Exception
if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null)
{
var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception));
var assignment = _F.Assignment(
_F.Local(ex),
_F.As(_F.Local(obj), ex.Type));
// better rethrow
rethrow = _F.Block(
ImmutableArray.Create(ex),
assignment,
_F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow),
// ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw();
_F.ExpressionStatement(
_F.Call(
_F.StaticCall(
exceptionDispatchInfoCapture.ContainingType,
exceptionDispatchInfoCapture,
_F.Local(ex)),
exceptionDispatchInfoThrow)));
}
return rethrow;
}
/// <summary>
/// Rewrites Try/Catch part of the Try/Catch/Finally
/// </summary>
private BoundStatement RewriteFinalizedRegion(BoundTryStatement node)
{
var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock);
var catches = node.CatchBlocks;
if (catches.IsDefaultOrEmpty)
{
return rewrittenTry;
}
var origAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var rewrittenCatches = this.VisitList(node.CatchBlocks);
BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches);
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame != null)
{
var handledLabel = _F.GenerateLabel("handled");
var handlersList = currentAwaitCatchFrame.handlers;
var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count);
for (int i = 0, l = handlersList.Count; i < l; i++)
{
handlers.Add(_F.SwitchSection(
i + 1,
_F.Block(
handlersList[i],
_F.Goto(handledLabel))));
}
tryWithCatches = _F.Block(
ImmutableArray.Create<LocalSymbol>(
currentAwaitCatchFrame.pendingCaughtException,
currentAwaitCatchFrame.pendingCatch).
AddRange(currentAwaitCatchFrame.GetHoistedLocals()),
_F.HiddenSequencePoint(),
_F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Default(currentAwaitCatchFrame.pendingCatch.Type)),
tryWithCatches,
_F.HiddenSequencePoint(),
_F.Switch(
_F.Local(currentAwaitCatchFrame.pendingCatch),
handlers.ToImmutableAndFree()),
_F.HiddenSequencePoint(),
_F.Label(handledLabel));
}
_currentAwaitCatchFrame = origAwaitCatchFrame;
return tryWithCatches;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
if (!_analysis.CatchContainsAwait(node))
{
var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var result = base.VisitCatchBlock(node);
_currentAwaitCatchFrame = origCurrentAwaitCatchFrame;
return result;
}
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame == null)
{
Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause));
var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent;
currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax);
}
var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object);
var catchTemp = _F.SynthesizedLocal(catchType);
var storePending = _F.AssignmentExpression(
_F.Local(currentAwaitCatchFrame.pendingCaughtException),
_F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type,
_F.Local(catchTemp)));
var setPendingCatchNum = _F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Literal(currentAwaitCatchFrame.handlers.Count + 1));
// catch (ExType exTemp)
// {
// pendingCaughtException = exTemp;
// catchNo = X;
// }
BoundCatchBlock catchAndPend;
ImmutableArray<LocalSymbol> handlerLocals;
var filterPrologueOpt = node.ExceptionFilterPrologueOpt;
var filterOpt = node.ExceptionFilterOpt;
if (filterOpt == null)
{
Debug.Assert(filterPrologueOpt is null);
// store pending exception
// as the first statement in a catch
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: filterPrologueOpt,
exceptionFilterOpt: null,
body: _F.Block(
_F.HiddenSequencePoint(),
_F.ExpressionStatement(storePending),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
// catch locals live on the synthetic catch handler block
handlerLocals = node.Locals;
}
else
{
handlerLocals = ImmutableArray<LocalSymbol>.Empty;
// catch locals move up into hoisted locals
// since we might need to access them from both the filter and the catch
foreach (var local in node.Locals)
{
currentAwaitCatchFrame.HoistLocal(local, _F);
}
// store pending exception
// as the first expression in a filter
var sourceOpt = node.ExceptionSourceOpt;
var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(filterOpt);
var newFilter = sourceOpt == null ?
_F.MakeSequence(
storePending,
rewrittenFilter) :
_F.MakeSequence(
storePending,
AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame),
rewrittenFilter);
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: rewrittenPrologue,
exceptionFilterOpt: newFilter,
body: _F.Block(
_F.HiddenSequencePoint(),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
}
var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance();
handlerStatements.Add(_F.HiddenSequencePoint());
if (filterOpt == null)
{
var sourceOpt = node.ExceptionSourceOpt;
if (sourceOpt != null)
{
BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame);
handlerStatements.Add(_F.ExpressionStatement(assignSource));
}
}
handlerStatements.Add((BoundStatement)this.Visit(node.Body));
var handler = _F.Block(
handlerLocals,
handlerStatements.ToImmutableAndFree()
);
currentAwaitCatchFrame.handlers.Add(handler);
return catchAndPend;
}
private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame)
{
BoundExpression assignSource = null;
if (rewrittenSource != null)
{
// exceptionSource = (exceptionSourceType)pendingCaughtException;
assignSource = _F.AssignmentExpression(
rewrittenSource,
_F.Convert(
rewrittenSource.Type,
_F.Local(currentAwaitCatchFrame.pendingCaughtException)));
}
return assignSource;
}
public override BoundNode VisitLocal(BoundLocal node)
{
var catchFrame = _currentAwaitCatchFrame;
LocalSymbol hoistedLocal;
if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal))
{
return base.VisitLocal(node);
}
return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type);
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null)
{
return base.VisitThrowStatement(node);
}
return Rethrow(_currentAwaitCatchFrame.pendingCaughtException);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLambda(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLocalFunctionStatement(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
private AwaitFinallyFrame PushFrame(BoundTryStatement statement)
{
var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax);
_currentAwaitFinallyFrame = newFrame;
return newFrame;
}
private void PopFrame()
{
var result = _currentAwaitFinallyFrame;
_currentAwaitFinallyFrame = result.ParentOpt;
}
/// <summary>
/// Analyzes method body for try blocks with awaits in finally blocks
/// Also collects labels that such blocks contain.
/// </summary>
private sealed class AwaitInFinallyAnalysis : LabelCollector
{
// all try blocks with yields in them and complete set of labels inside those try blocks
// NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included
// in the label set of the nearest yielding-try parent
private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry;
private HashSet<BoundCatchBlock> _awaitContainingCatches;
// transient accumulators.
private bool _seenAwait;
public AwaitInFinallyAnalysis(BoundStatement body)
{
_seenAwait = false;
this.Visit(body);
}
/// <summary>
/// Returns true if a finally of the given try contains awaits
/// </summary>
public bool FinallyContainsAwaits(BoundTryStatement statement)
{
return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement);
}
/// <summary>
/// Returns true if a catch contains awaits
/// </summary>
internal bool CatchContainsAwait(BoundCatchBlock node)
{
return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node);
}
/// <summary>
/// Returns true if body contains await in a finally block.
/// </summary>
public bool ContainsAwaitInHandlers()
{
return _labelsInInterestingTry != null || _awaitContainingCatches != null;
}
/// <summary>
/// Labels reachable from within this frame without invoking its finally.
/// null if there are no such labels.
/// </summary>
internal HashSet<LabelSymbol> Labels(BoundTryStatement statement)
{
return _labelsInInterestingTry[statement];
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var origLabels = this.currentLabels;
this.currentLabels = null;
Visit(node.TryBlock);
VisitList(node.CatchBlocks);
var origSeenAwait = _seenAwait;
_seenAwait = false;
Visit(node.FinallyBlockOpt);
if (_seenAwait)
{
// this try has awaits in the finally !
var labelsInInterestingTry = _labelsInInterestingTry;
if (labelsInInterestingTry == null)
{
_labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>();
}
labelsInInterestingTry.Add(node, currentLabels);
currentLabels = origLabels;
}
else
{
// this is a boring try without awaits in finally
// currentLabels = currentLabels U origLabels ;
if (currentLabels == null)
{
currentLabels = origLabels;
}
else if (origLabels != null)
{
currentLabels.UnionWith(origLabels);
}
}
_seenAwait = _seenAwait | origSeenAwait;
return null;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
var origSeenAwait = _seenAwait;
_seenAwait = false;
var result = base.VisitCatchBlock(node);
if (_seenAwait)
{
var awaitContainingCatches = _awaitContainingCatches;
if (awaitContainingCatches == null)
{
_awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>();
}
_awaitContainingCatches.Add(node);
}
_seenAwait |= origSeenAwait;
return result;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
_seenAwait = true;
return base.VisitAwaitExpression(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLambda(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLocalFunctionStatement(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
}
// storage of various information about a given finally frame
private sealed class AwaitFinallyFrame
{
// Enclosing frame. Root frame does not have parent.
public readonly AwaitFinallyFrame ParentOpt;
// labels within this frame (branching to these labels does not go through finally).
public readonly HashSet<LabelSymbol> LabelsOpt;
// the try or using-await statement the frame is associated with
private readonly StatementSyntax _statementSyntaxOpt;
// proxy labels for branches leaving the frame.
// we build this on demand once we encounter leaving branches.
// subsequent leaves to an already proxied label redirected to the proxy.
// At the proxy label we will execute finally and forward the control flow
// to the actual destination. (which could be proxied again in the parent)
public Dictionary<LabelSymbol, LabelSymbol> proxyLabels;
public List<LabelSymbol> proxiedLabels;
public GeneratedLabelSymbol returnProxyLabel;
public SynthesizedLocal returnValue;
public AwaitFinallyFrame()
{
// root frame
}
public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax)
{
Debug.Assert(parent != null);
Debug.Assert(statementSyntax != null);
Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement ||
(statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default));
this.ParentOpt = parent;
this.LabelsOpt = labelsOpt;
_statementSyntaxOpt = statementSyntax;
}
public bool IsRoot()
{
return this.ParentOpt == null;
}
// returns a proxy for a label if branch must be hijacked to run finally
// otherwise returns same label back
public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label)
{
// no need to proxy a label in the current frame or when we are at the root
if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label)))
{
return label;
}
var proxyLabels = this.proxyLabels;
var proxiedLabels = this.proxiedLabels;
if (proxyLabels == null)
{
this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>();
this.proxiedLabels = proxiedLabels = new List<LabelSymbol>();
}
LabelSymbol proxy;
if (!proxyLabels.TryGetValue(label, out proxy))
{
proxy = new GeneratedLabelSymbol("proxy" + label.Name);
proxyLabels.Add(label, proxy);
proxiedLabels.Add(label);
}
return proxy;
}
public LabelSymbol ProxyReturnIfNeeded(
MethodSymbol containingMethod,
BoundExpression valueOpt,
out SynthesizedLocal returnValue)
{
returnValue = null;
// no need to proxy returns at the root
if (this.IsRoot())
{
return null;
}
var returnProxy = this.returnProxyLabel;
if (returnProxy == null)
{
this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy");
}
if (valueOpt != null)
{
returnValue = this.returnValue;
if (returnValue == null)
{
Debug.Assert(_statementSyntaxOpt != null);
this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt);
}
}
return returnProxy;
}
}
private sealed class AwaitCatchFrame
{
// object, stores the original caught exception
// used to initialize the exception source inside the handler
// also used in rethrow statements
public readonly SynthesizedLocal pendingCaughtException;
// int, stores the number of pending catch
// 0 - means no catches are pending.
public readonly SynthesizedLocal pendingCatch;
// synthetic handlers produced by catch rewrite.
// they will become switch sections when pending exception is dispatched.
public readonly List<BoundBlock> handlers;
// when catch local must be used from a filter
// we need to "hoist" it up to ensure that both the filter
// and the catch access the same variable.
// NOTE: it must be the same variable, not just same value.
// The difference would be observable if filter mutates the variable
// or/and if a variable gets lifted into a closure.
private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals;
private readonly List<LocalSymbol> _orderedHoistedLocals;
public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax)
{
this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax);
this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax);
this.handlers = new List<BoundBlock>();
_hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>();
_orderedHoistedLocals = new List<LocalSymbol>();
}
public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F)
{
if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2)))
{
_hoistedLocals.Add(local, local);
_orderedHoistedLocals.Add(local);
return;
}
// code uses "await" in two sibling catches with exception filters
// locals with same names and types may cause problems if they are lifted
// and become fields with identical signatures.
// To avoid such problems we will mangle the name of the second local.
// This will only affect debugging of this extremely rare case.
Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement));
var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal);
_hoistedLocals.Add(local, newLocal);
_orderedHoistedLocals.Add(newLocal);
}
public IEnumerable<LocalSymbol> GetHoistedLocals()
{
return _orderedHoistedLocals;
}
public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal)
{
return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The purpose of this rewriter is to replace await-containing catch and finally handlers
/// with surrogate replacements that keep actual handler code in regular code blocks.
/// That allows these constructs to be further lowered at the async lowering pass.
/// </summary>
internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private readonly SyntheticBoundNodeFactory _F;
private readonly AwaitInFinallyAnalysis _analysis;
private AwaitCatchFrame _currentAwaitCatchFrame;
private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame();
private AsyncExceptionHandlerRewriter(
MethodSymbol containingMethod,
NamedTypeSymbol containingType,
SyntheticBoundNodeFactory factory,
AwaitInFinallyAnalysis analysis)
{
_F = factory;
_F.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_analysis = analysis;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// The goal is to not have exception handlers that contain awaits in them.
///
/// 1) Await containing finally blocks:
/// The general strategy is to rewrite await containing handlers into synthetic handlers.
/// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them.
/// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually
/// (this is the hard part of the rewrite).
///
/// try{
/// code;
/// }finally{
/// handler;
/// }
///
/// Into ===>
///
/// Exception ex = null;
/// int pendingBranch = 0;
///
/// try{
/// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel
/// goto finallyLabel;
/// }catch (ex){ // essentially pend the currently active exception
/// };
///
/// finallyLabel:
/// {
/// handler;
/// if (ex != null) throw ex; // unpend the exception
/// unpend branches/return
/// }
///
/// 2) Await containing catches:
/// try{
/// code;
/// }catch (Exception ex){
/// handler;
/// throw;
/// }
///
///
/// Into ===>
///
/// Object pendingException;
/// int pendingCatch = 0;
///
/// try{
/// code;
/// }catch (Exception temp){ // essentially pend the currently active exception
/// pendingException = temp;
/// pendingCatch = 1;
/// };
///
/// switch(pendingCatch):
/// {
/// case 1:
/// {
/// Exception ex = (Exception)pendingException;
/// handler;
/// throw pendingException
/// }
/// }
/// </summary>
public static BoundStatement Rewrite(
MethodSymbol containingSymbol,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(containingSymbol != null);
Debug.Assert((object)containingType != null);
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
var analysis = new AwaitInFinallyAnalysis(statement);
if (!analysis.ContainsAwaitInHandlers())
{
return statement;
}
var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics);
var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis);
var loweredStatement = (BoundStatement)rewriter.Visit(statement);
return loweredStatement;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var tryStatementSyntax = node.Syntax;
// If you add a syntax kind to the assertion below, please also ensure
// that the scenario has been tested with Edit-and-Continue.
Debug.Assert(
tryStatementSyntax.IsKind(SyntaxKind.TryStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LockStatement));
BoundStatement finalizedRegion;
BoundBlock rewrittenFinally;
var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node);
if (!finallyContainsAwaits)
{
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt);
if (rewrittenFinally == null)
{
return finalizedRegion;
}
var asTry = finalizedRegion as BoundTryStatement;
if (asTry != null)
{
// since finalized region is a try we can just attach finally to it
Debug.Assert(asTry.FinallyBlockOpt == null);
return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler);
}
else
{
// wrap finalizedRegion into a Try with a finally.
return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally);
}
}
// rewrite finalized region (try and catches) in the current frame
var frame = PushFrame(node);
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt);
PopFrame();
var exceptionType = _F.SpecialType(SpecialType.System_Object);
var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax);
var finallyLabel = _F.GenerateLabel("finallyLabel");
var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax);
var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block());
var catchAndPendException = _F.Try(
_F.Block(
finalizedRegion,
_F.HiddenSequencePoint(),
_F.Goto(finallyLabel),
PendBranches(frame, pendingBranchVar, finallyLabel)),
ImmutableArray.Create(catchAll),
finallyLabel: finallyLabel);
BoundBlock syntheticFinallyBlock = _F.Block(
_F.HiddenSequencePoint(),
_F.Label(finallyLabel),
rewrittenFinally,
_F.HiddenSequencePoint(),
UnpendException(pendingExceptionLocal),
UnpendBranches(
frame,
pendingBranchVar,
pendingExceptionLocal));
BoundStatement syntheticFinally = syntheticFinallyBlock;
if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator)
{
// We wrap this block so that it can be processed as a finally block by async-iterator rewriting
syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock);
}
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(_F.HiddenSequencePoint());
locals.Add(pendingExceptionLocal);
statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type)));
locals.Add(pendingBranchVar);
statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type)));
LocalSymbol returnLocal = frame.returnValue;
if (returnLocal != null)
{
locals.Add(returnLocal);
}
statements.Add(catchAndPendException);
statements.Add(syntheticFinally);
var completeTry = _F.Block(
locals.ToImmutableAndFree(),
statements.ToImmutableAndFree());
return completeTry;
}
private BoundBlock PendBranches(
AwaitFinallyFrame frame,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance();
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
var proxyLabels = frame.proxyLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var proxied = proxiedLabels[i - 1];
var proxy = proxyLabels[proxied];
PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel);
}
}
var returnProxy = frame.returnProxyLabel;
if (returnProxy != null)
{
PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel);
}
return _F.Block(bodyStatements.ToImmutableAndFree());
}
private void PendBranch(
ArrayBuilder<BoundStatement> bodyStatements,
LabelSymbol proxy,
int i,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
// branch lands here
bodyStatements.Add(_F.Label(proxy));
// pend the branch
bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i)));
// skip other proxies
bodyStatements.Add(_F.Goto(finallyLabel));
}
private BoundStatement UnpendBranches(
AwaitFinallyFrame frame,
SynthesizedLocal pendingBranchVar,
SynthesizedLocal pendingException)
{
var parent = frame.ParentOpt;
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance();
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var target = proxiedLabels[i - 1];
var parentProxy = parent.ProxyLabelIfNeeded(target);
var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy));
cases.Add(caseStatement);
}
}
if (frame.returnProxyLabel != null)
{
BoundLocal pendingValue = null;
if (frame.returnValue != null)
{
pendingValue = _F.Local(frame.returnValue);
}
SynthesizedLocal returnValue;
BoundStatement unpendReturn;
var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue);
if (returnLabel == null)
{
unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue);
}
else
{
if (pendingValue == null)
{
unpendReturn = _F.Goto(returnLabel);
}
else
{
unpendReturn = _F.Block(
_F.Assignment(
_F.Local(returnValue),
pendingValue),
_F.Goto(returnLabel));
}
}
var caseStatement = _F.SwitchSection(i, unpendReturn);
cases.Add(caseStatement);
}
return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree());
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt);
BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt);
var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label);
return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?");
return base.VisitConditionalGoto(node);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
SynthesizedLocal returnValue;
var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded(
_F.CurrentFunction,
node.ExpressionOpt,
out returnValue);
if (returnLabel == null)
{
return base.VisitReturnStatement(node);
}
var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt));
if (returnExpr != null)
{
return _F.Block(
_F.Assignment(
_F.Local(returnValue),
returnExpr),
_F.Goto(
returnLabel));
}
else
{
return _F.Goto(returnLabel);
}
}
private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal)
{
// create a temp.
// pendingExceptionLocal will certainly be captured, no need to access it over and over.
LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object));
var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal));
// throw pendingExceptionLocal;
BoundStatement rethrow = Rethrow(obj);
return _F.Block(
ImmutableArray.Create<LocalSymbol>(obj),
objInit,
_F.If(
_F.ObjectNotEqual(
_F.Local(obj),
_F.Null(obj.Type)),
rethrow));
}
private BoundStatement Rethrow(LocalSymbol obj)
{
// conservative rethrow
BoundStatement rethrow = _F.Throw(_F.Local(obj));
var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true);
var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true);
// if these helpers are available, we can rethrow with original stack info
// as long as it derives from Exception
if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null)
{
var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception));
var assignment = _F.Assignment(
_F.Local(ex),
_F.As(_F.Local(obj), ex.Type));
// better rethrow
rethrow = _F.Block(
ImmutableArray.Create(ex),
assignment,
_F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow),
// ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw();
_F.ExpressionStatement(
_F.Call(
_F.StaticCall(
exceptionDispatchInfoCapture.ContainingType,
exceptionDispatchInfoCapture,
_F.Local(ex)),
exceptionDispatchInfoThrow)));
}
return rethrow;
}
/// <summary>
/// Rewrites Try/Catch part of the Try/Catch/Finally
/// </summary>
private BoundStatement RewriteFinalizedRegion(BoundTryStatement node)
{
var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock);
var catches = node.CatchBlocks;
if (catches.IsDefaultOrEmpty)
{
return rewrittenTry;
}
var origAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var rewrittenCatches = this.VisitList(node.CatchBlocks);
BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches);
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame != null)
{
var handledLabel = _F.GenerateLabel("handled");
var handlersList = currentAwaitCatchFrame.handlers;
var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count);
for (int i = 0, l = handlersList.Count; i < l; i++)
{
handlers.Add(_F.SwitchSection(
i + 1,
_F.Block(
handlersList[i],
_F.Goto(handledLabel))));
}
tryWithCatches = _F.Block(
ImmutableArray.Create<LocalSymbol>(
currentAwaitCatchFrame.pendingCaughtException,
currentAwaitCatchFrame.pendingCatch).
AddRange(currentAwaitCatchFrame.GetHoistedLocals()),
_F.HiddenSequencePoint(),
_F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Default(currentAwaitCatchFrame.pendingCatch.Type)),
tryWithCatches,
_F.HiddenSequencePoint(),
_F.Switch(
_F.Local(currentAwaitCatchFrame.pendingCatch),
handlers.ToImmutableAndFree()),
_F.HiddenSequencePoint(),
_F.Label(handledLabel));
}
_currentAwaitCatchFrame = origAwaitCatchFrame;
return tryWithCatches;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
if (!_analysis.CatchContainsAwait(node))
{
var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var result = base.VisitCatchBlock(node);
_currentAwaitCatchFrame = origCurrentAwaitCatchFrame;
return result;
}
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame == null)
{
Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause));
var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent;
currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax);
}
var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object);
var catchTemp = _F.SynthesizedLocal(catchType);
var storePending = _F.AssignmentExpression(
_F.Local(currentAwaitCatchFrame.pendingCaughtException),
_F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type,
_F.Local(catchTemp)));
var setPendingCatchNum = _F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Literal(currentAwaitCatchFrame.handlers.Count + 1));
// catch (ExType exTemp)
// {
// pendingCaughtException = exTemp;
// catchNo = X;
// }
BoundCatchBlock catchAndPend;
ImmutableArray<LocalSymbol> handlerLocals;
var filterPrologueOpt = node.ExceptionFilterPrologueOpt;
var filterOpt = node.ExceptionFilterOpt;
if (filterOpt == null)
{
Debug.Assert(filterPrologueOpt is null);
// store pending exception
// as the first statement in a catch
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: filterPrologueOpt,
exceptionFilterOpt: null,
body: _F.Block(
_F.HiddenSequencePoint(),
_F.ExpressionStatement(storePending),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
// catch locals live on the synthetic catch handler block
handlerLocals = node.Locals;
}
else
{
handlerLocals = ImmutableArray<LocalSymbol>.Empty;
// catch locals move up into hoisted locals
// since we might need to access them from both the filter and the catch
foreach (var local in node.Locals)
{
currentAwaitCatchFrame.HoistLocal(local, _F);
}
// store pending exception
// as the first expression in a filter
var sourceOpt = node.ExceptionSourceOpt;
var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(filterOpt);
var newFilter = sourceOpt == null ?
_F.MakeSequence(
storePending,
rewrittenFilter) :
_F.MakeSequence(
storePending,
AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame),
rewrittenFilter);
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: rewrittenPrologue,
exceptionFilterOpt: newFilter,
body: _F.Block(
_F.HiddenSequencePoint(),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
}
var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance();
handlerStatements.Add(_F.HiddenSequencePoint());
if (filterOpt == null)
{
var sourceOpt = node.ExceptionSourceOpt;
if (sourceOpt != null)
{
BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame);
handlerStatements.Add(_F.ExpressionStatement(assignSource));
}
}
handlerStatements.Add((BoundStatement)this.Visit(node.Body));
var handler = _F.Block(
handlerLocals,
handlerStatements.ToImmutableAndFree()
);
currentAwaitCatchFrame.handlers.Add(handler);
return catchAndPend;
}
private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame)
{
BoundExpression assignSource = null;
if (rewrittenSource != null)
{
// exceptionSource = (exceptionSourceType)pendingCaughtException;
assignSource = _F.AssignmentExpression(
rewrittenSource,
_F.Convert(
rewrittenSource.Type,
_F.Local(currentAwaitCatchFrame.pendingCaughtException)));
}
return assignSource;
}
public override BoundNode VisitLocal(BoundLocal node)
{
var catchFrame = _currentAwaitCatchFrame;
LocalSymbol hoistedLocal;
if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal))
{
return base.VisitLocal(node);
}
return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type);
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null)
{
return base.VisitThrowStatement(node);
}
return Rethrow(_currentAwaitCatchFrame.pendingCaughtException);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLambda(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLocalFunctionStatement(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
private AwaitFinallyFrame PushFrame(BoundTryStatement statement)
{
var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax);
_currentAwaitFinallyFrame = newFrame;
return newFrame;
}
private void PopFrame()
{
var result = _currentAwaitFinallyFrame;
_currentAwaitFinallyFrame = result.ParentOpt;
}
/// <summary>
/// Analyzes method body for try blocks with awaits in finally blocks
/// Also collects labels that such blocks contain.
/// </summary>
private sealed class AwaitInFinallyAnalysis : LabelCollector
{
// all try blocks with yields in them and complete set of labels inside those try blocks
// NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included
// in the label set of the nearest yielding-try parent
private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry;
private HashSet<BoundCatchBlock> _awaitContainingCatches;
// transient accumulators.
private bool _seenAwait;
public AwaitInFinallyAnalysis(BoundStatement body)
{
_seenAwait = false;
this.Visit(body);
}
/// <summary>
/// Returns true if a finally of the given try contains awaits
/// </summary>
public bool FinallyContainsAwaits(BoundTryStatement statement)
{
return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement);
}
/// <summary>
/// Returns true if a catch contains awaits
/// </summary>
internal bool CatchContainsAwait(BoundCatchBlock node)
{
return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node);
}
/// <summary>
/// Returns true if body contains await in a finally block.
/// </summary>
public bool ContainsAwaitInHandlers()
{
return _labelsInInterestingTry != null || _awaitContainingCatches != null;
}
/// <summary>
/// Labels reachable from within this frame without invoking its finally.
/// null if there are no such labels.
/// </summary>
internal HashSet<LabelSymbol> Labels(BoundTryStatement statement)
{
return _labelsInInterestingTry[statement];
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var origLabels = this.currentLabels;
this.currentLabels = null;
Visit(node.TryBlock);
VisitList(node.CatchBlocks);
var origSeenAwait = _seenAwait;
_seenAwait = false;
Visit(node.FinallyBlockOpt);
if (_seenAwait)
{
// this try has awaits in the finally !
var labelsInInterestingTry = _labelsInInterestingTry;
if (labelsInInterestingTry == null)
{
_labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>();
}
labelsInInterestingTry.Add(node, currentLabels);
currentLabels = origLabels;
}
else
{
// this is a boring try without awaits in finally
// currentLabels = currentLabels U origLabels ;
if (currentLabels == null)
{
currentLabels = origLabels;
}
else if (origLabels != null)
{
currentLabels.UnionWith(origLabels);
}
}
_seenAwait = _seenAwait | origSeenAwait;
return null;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
var origSeenAwait = _seenAwait;
_seenAwait = false;
var result = base.VisitCatchBlock(node);
if (_seenAwait)
{
var awaitContainingCatches = _awaitContainingCatches;
if (awaitContainingCatches == null)
{
_awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>();
}
_awaitContainingCatches.Add(node);
}
_seenAwait |= origSeenAwait;
return result;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
_seenAwait = true;
return base.VisitAwaitExpression(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLambda(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLocalFunctionStatement(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
}
// storage of various information about a given finally frame
private sealed class AwaitFinallyFrame
{
// Enclosing frame. Root frame does not have parent.
public readonly AwaitFinallyFrame ParentOpt;
// labels within this frame (branching to these labels does not go through finally).
public readonly HashSet<LabelSymbol> LabelsOpt;
// the try or using-await statement the frame is associated with
private readonly StatementSyntax _statementSyntaxOpt;
// proxy labels for branches leaving the frame.
// we build this on demand once we encounter leaving branches.
// subsequent leaves to an already proxied label redirected to the proxy.
// At the proxy label we will execute finally and forward the control flow
// to the actual destination. (which could be proxied again in the parent)
public Dictionary<LabelSymbol, LabelSymbol> proxyLabels;
public List<LabelSymbol> proxiedLabels;
public GeneratedLabelSymbol returnProxyLabel;
public SynthesizedLocal returnValue;
public AwaitFinallyFrame()
{
// root frame
}
public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax)
{
Debug.Assert(parent != null);
Debug.Assert(statementSyntax != null);
Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement ||
(statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default));
this.ParentOpt = parent;
this.LabelsOpt = labelsOpt;
_statementSyntaxOpt = statementSyntax;
}
public bool IsRoot()
{
return this.ParentOpt == null;
}
// returns a proxy for a label if branch must be hijacked to run finally
// otherwise returns same label back
public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label)
{
// no need to proxy a label in the current frame or when we are at the root
if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label)))
{
return label;
}
var proxyLabels = this.proxyLabels;
var proxiedLabels = this.proxiedLabels;
if (proxyLabels == null)
{
this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>();
this.proxiedLabels = proxiedLabels = new List<LabelSymbol>();
}
LabelSymbol proxy;
if (!proxyLabels.TryGetValue(label, out proxy))
{
proxy = new GeneratedLabelSymbol("proxy" + label.Name);
proxyLabels.Add(label, proxy);
proxiedLabels.Add(label);
}
return proxy;
}
public LabelSymbol ProxyReturnIfNeeded(
MethodSymbol containingMethod,
BoundExpression valueOpt,
out SynthesizedLocal returnValue)
{
returnValue = null;
// no need to proxy returns at the root
if (this.IsRoot())
{
return null;
}
var returnProxy = this.returnProxyLabel;
if (returnProxy == null)
{
this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy");
}
if (valueOpt != null)
{
returnValue = this.returnValue;
if (returnValue == null)
{
Debug.Assert(_statementSyntaxOpt != null);
this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt);
}
}
return returnProxy;
}
}
private sealed class AwaitCatchFrame
{
// object, stores the original caught exception
// used to initialize the exception source inside the handler
// also used in rethrow statements
public readonly SynthesizedLocal pendingCaughtException;
// int, stores the number of pending catch
// 0 - means no catches are pending.
public readonly SynthesizedLocal pendingCatch;
// synthetic handlers produced by catch rewrite.
// they will become switch sections when pending exception is dispatched.
public readonly List<BoundBlock> handlers;
// when catch local must be used from a filter
// we need to "hoist" it up to ensure that both the filter
// and the catch access the same variable.
// NOTE: it must be the same variable, not just same value.
// The difference would be observable if filter mutates the variable
// or/and if a variable gets lifted into a closure.
private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals;
private readonly List<LocalSymbol> _orderedHoistedLocals;
public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax)
{
this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax);
this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax);
this.handlers = new List<BoundBlock>();
_hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>();
_orderedHoistedLocals = new List<LocalSymbol>();
}
public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F)
{
if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2)))
{
_hoistedLocals.Add(local, local);
_orderedHoistedLocals.Add(local);
return;
}
// code uses "await" in two sibling catches with exception filters
// locals with same names and types may cause problems if they are lifted
// and become fields with identical signatures.
// To avoid such problems we will mangle the name of the second local.
// This will only affect debugging of this extremely rare case.
Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement));
var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal);
_hoistedLocals.Add(local, newLocal);
_orderedHoistedLocals.Add(newLocal);
}
public IEnumerable<LocalSymbol> GetHoistedLocals()
{
return _orderedHoistedLocals;
}
public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal)
{
return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal);
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/Core/MSBuild/Host/Mef/MSBuildMefHostServices.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
using System.Threading;
namespace Microsoft.CodeAnalysis.Host.Mef
{
public static class MSBuildMefHostServices
{
private static MefHostServices s_defaultServices;
public static MefHostServices DefaultServices
{
get
{
if (s_defaultServices == null)
{
Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null);
}
return s_defaultServices;
}
}
private static ImmutableArray<Assembly> s_defaultAssemblies;
public static ImmutableArray<Assembly> DefaultAssemblies
{
get
{
if (s_defaultAssemblies == null)
{
ImmutableInterlocked.InterlockedCompareExchange(ref s_defaultAssemblies, CreateDefaultAssemblies(), default);
}
return s_defaultAssemblies;
}
}
private static ImmutableArray<Assembly> CreateDefaultAssemblies()
{
var assemblyNames = new string[]
{
typeof(MSBuildMefHostServices).Assembly.GetName().Name,
};
return MefHostServices.DefaultAssemblies.Concat(
MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames));
}
internal readonly struct TestAccessor
{
/// <summary>
/// Allows tests to clear services between runs.
/// </summary>
internal static void ClearCachedServices()
{
// The existing host, if any, is not retained past this call.
s_defaultServices = null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Reflection;
using System.Threading;
namespace Microsoft.CodeAnalysis.Host.Mef
{
public static class MSBuildMefHostServices
{
private static MefHostServices s_defaultServices;
public static MefHostServices DefaultServices
{
get
{
if (s_defaultServices == null)
{
Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null);
}
return s_defaultServices;
}
}
private static ImmutableArray<Assembly> s_defaultAssemblies;
public static ImmutableArray<Assembly> DefaultAssemblies
{
get
{
if (s_defaultAssemblies == null)
{
ImmutableInterlocked.InterlockedCompareExchange(ref s_defaultAssemblies, CreateDefaultAssemblies(), default);
}
return s_defaultAssemblies;
}
}
private static ImmutableArray<Assembly> CreateDefaultAssemblies()
{
var assemblyNames = new string[]
{
typeof(MSBuildMefHostServices).Assembly.GetName().Name,
};
return MefHostServices.DefaultAssemblies.Concat(
MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames));
}
internal readonly struct TestAccessor
{
/// <summary>
/// Allows tests to clear services between runs.
/// </summary>
internal static void ClearCachedServices()
{
// The existing host, if any, is not retained past this call.
s_defaultServices = null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Tools/AnalyzerRunner/AssemblyLoader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Reflection;
using Microsoft.CodeAnalysis;
namespace AnalyzerRunner
{
internal class AssemblyLoader : IAnalyzerAssemblyLoader
{
public static AssemblyLoader Instance = new AssemblyLoader();
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
return Assembly.LoadFrom(fullPath);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Reflection;
using Microsoft.CodeAnalysis;
namespace AnalyzerRunner
{
internal class AssemblyLoader : IAnalyzerAssemblyLoader
{
public static AssemblyLoader Instance = new AssemblyLoader();
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
return Assembly.LoadFrom(fullPath);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/Core.Wpf/Interactive/InteractiveGlobalUndoServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive
{
[ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), WorkspaceKind.Interactive), Shared]
internal sealed class InteractiveGlobalUndoServiceFactory : IWorkspaceServiceFactory
{
private readonly GlobalUndoService _singleton;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveGlobalUndoServiceFactory(ITextUndoHistoryRegistry undoHistoryRegistry)
=> _singleton = new GlobalUndoService(undoHistoryRegistry);
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> _singleton;
private class GlobalUndoService : IGlobalUndoService
{
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
public bool IsGlobalTransactionOpen(Workspace workspace)
=> GetHistory(workspace).CurrentTransaction != null;
public GlobalUndoService(ITextUndoHistoryRegistry undoHistoryRegistry)
=> _undoHistoryRegistry = undoHistoryRegistry;
public bool CanUndo(Workspace workspace)
{
// only primary workspace supports global undo
return workspace is InteractiveWindowWorkspace;
}
public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description)
{
if (!CanUndo(workspace))
{
throw new ArgumentException(EditorFeaturesResources.Given_Workspace_doesn_t_support_Undo);
}
var textUndoHistory = GetHistory(workspace);
var transaction = textUndoHistory.CreateTransaction(description);
return new InteractiveGlobalUndoTransaction(transaction);
}
private ITextUndoHistory GetHistory(Workspace workspace)
{
var interactiveWorkspace = (InteractiveWindowWorkspace)workspace;
var textBuffer = interactiveWorkspace.Window.TextView.TextBuffer;
Contract.ThrowIfFalse(_undoHistoryRegistry.TryGetHistory(textBuffer, out var textUndoHistory));
return textUndoHistory;
}
private class InteractiveGlobalUndoTransaction : IWorkspaceGlobalUndoTransaction
{
private readonly ITextUndoTransaction _transaction;
public InteractiveGlobalUndoTransaction(ITextUndoTransaction transaction)
=> _transaction = transaction;
public void AddDocument(DocumentId id)
{
// Nothing to do.
}
public void Commit()
=> _transaction.Complete();
public void Dispose()
=> _transaction.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.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive
{
[ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), WorkspaceKind.Interactive), Shared]
internal sealed class InteractiveGlobalUndoServiceFactory : IWorkspaceServiceFactory
{
private readonly GlobalUndoService _singleton;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveGlobalUndoServiceFactory(ITextUndoHistoryRegistry undoHistoryRegistry)
=> _singleton = new GlobalUndoService(undoHistoryRegistry);
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> _singleton;
private class GlobalUndoService : IGlobalUndoService
{
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
public bool IsGlobalTransactionOpen(Workspace workspace)
=> GetHistory(workspace).CurrentTransaction != null;
public GlobalUndoService(ITextUndoHistoryRegistry undoHistoryRegistry)
=> _undoHistoryRegistry = undoHistoryRegistry;
public bool CanUndo(Workspace workspace)
{
// only primary workspace supports global undo
return workspace is InteractiveWindowWorkspace;
}
public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description)
{
if (!CanUndo(workspace))
{
throw new ArgumentException(EditorFeaturesResources.Given_Workspace_doesn_t_support_Undo);
}
var textUndoHistory = GetHistory(workspace);
var transaction = textUndoHistory.CreateTransaction(description);
return new InteractiveGlobalUndoTransaction(transaction);
}
private ITextUndoHistory GetHistory(Workspace workspace)
{
var interactiveWorkspace = (InteractiveWindowWorkspace)workspace;
var textBuffer = interactiveWorkspace.Window.TextView.TextBuffer;
Contract.ThrowIfFalse(_undoHistoryRegistry.TryGetHistory(textBuffer, out var textUndoHistory));
return textUndoHistory;
}
private class InteractiveGlobalUndoTransaction : IWorkspaceGlobalUndoTransaction
{
private readonly ITextUndoTransaction _transaction;
public InteractiveGlobalUndoTransaction(ITextUndoTransaction transaction)
=> _transaction = transaction;
public void AddDocument(DocumentId id)
{
// Nothing to do.
}
public void Commit()
=> _transaction.Complete();
public void Dispose()
=> _transaction.Dispose();
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Portable/Binder/LoopBinderContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class LoopBinder : LocalScopeBinder
{
private readonly GeneratedLabelSymbol _breakLabel;
private readonly GeneratedLabelSymbol _continueLabel;
protected LoopBinder(Binder enclosing)
: base(enclosing)
{
_breakLabel = new GeneratedLabelSymbol("break");
_continueLabel = new GeneratedLabelSymbol("continue");
}
internal override GeneratedLabelSymbol BreakLabel
{
get
{
return _breakLabel;
}
}
internal override GeneratedLabelSymbol ContinueLabel
{
get
{
return _continueLabel;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class LoopBinder : LocalScopeBinder
{
private readonly GeneratedLabelSymbol _breakLabel;
private readonly GeneratedLabelSymbol _continueLabel;
protected LoopBinder(Binder enclosing)
: base(enclosing)
{
_breakLabel = new GeneratedLabelSymbol("break");
_continueLabel = new GeneratedLabelSymbol("continue");
}
internal override GeneratedLabelSymbol BreakLabel
{
get
{
return _breakLabel;
}
}
internal override GeneratedLabelSymbol ContinueLabel
{
get
{
return _continueLabel;
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/CSharp/Portable/UsePatternMatching/CSharpIsAndCastCheckWithoutNameCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
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.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternMatchingIsAndCastCheckWithoutName), Shared]
internal partial class CSharpIsAndCastCheckWithoutNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpIsAndCastCheckWithoutNameCodeFixProvider()
: base(supportsFixAll: false)
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
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)
{
Debug.Assert(diagnostics.Length == 1);
var location = diagnostics[0].Location;
var isExpression = (BinaryExpressionSyntax)location.FindNode(
getInnermostNodeForTie: true, cancellationToken: cancellationToken);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var (matches, localName) = CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer.Instance.AnalyzeExpression(
semanticModel, isExpression, cancellationToken);
var updatedSemanticModel = CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer.ReplaceMatches(
semanticModel, isExpression, localName, matches, cancellationToken);
var updatedRoot = updatedSemanticModel.SyntaxTree.GetRoot(cancellationToken);
editor.ReplaceNode(editor.OriginalRoot, updatedRoot);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_pattern_matching, createChangedDocument, nameof(CSharpIsAndCastCheckWithoutNameCodeFixProvider))
{
}
internal override CodeActionPriority Priority => CodeActionPriority.Low;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
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.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternMatchingIsAndCastCheckWithoutName), Shared]
internal partial class CSharpIsAndCastCheckWithoutNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpIsAndCastCheckWithoutNameCodeFixProvider()
: base(supportsFixAll: false)
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.InlineIsTypeWithoutNameCheckDiagnosticsId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
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)
{
Debug.Assert(diagnostics.Length == 1);
var location = diagnostics[0].Location;
var isExpression = (BinaryExpressionSyntax)location.FindNode(
getInnermostNodeForTie: true, cancellationToken: cancellationToken);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var (matches, localName) = CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer.Instance.AnalyzeExpression(
semanticModel, isExpression, cancellationToken);
var updatedSemanticModel = CSharpIsAndCastCheckWithoutNameDiagnosticAnalyzer.ReplaceMatches(
semanticModel, isExpression, localName, matches, cancellationToken);
var updatedRoot = updatedSemanticModel.SyntaxTree.GetRoot(cancellationToken);
editor.ReplaceNode(editor.OriginalRoot, updatedRoot);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Use_pattern_matching, createChangedDocument, nameof(CSharpIsAndCastCheckWithoutNameCodeFixProvider))
{
}
internal override CodeActionPriority Priority => CodeActionPriority.Low;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/VisualBasic/Portable/Structure/Providers/ForBlockStructureProvider.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 ForBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of ForBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As ForBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.ForOrForEachStatement, autoCollapse:=False,
type:=BlockTypes.Loop, isCollapsible:=True))
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 ForBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of ForBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As ForBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.ForOrForEachStatement, autoCollapse:=False,
type:=BlockTypes.Loop, isCollapsible:=True))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MockDiagnosticAnalyzer
{
public partial class MockDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string Id = "MockDiagnostic";
private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
=> context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
=> context.RegisterCompilationEndAction(AnalyzeCompilation);
public void AnalyzeCompilation(CompilationAnalysisContext context)
{
}
}
public MockDiagnosticAnalyzerTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new MockDiagnosticAnalyzer(), null);
private async Task VerifyDiagnosticsAsync(
string source,
params DiagnosticDescription[] expectedDiagnostics)
{
using var workspace = TestWorkspace.CreateCSharp(source, composition: GetComposition());
var actualDiagnostics = await this.GetDiagnosticsAsync(workspace, new TestParameters());
actualDiagnostics.Verify(expectedDiagnostics);
}
[WorkItem(906919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/906919")]
[Fact]
public async Task Bug906919()
{
var source = "[|class C { }|]";
await VerifyDiagnosticsAsync(source);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MockDiagnosticAnalyzer
{
public partial class MockDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string Id = "MockDiagnostic";
private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
=> context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
=> context.RegisterCompilationEndAction(AnalyzeCompilation);
public void AnalyzeCompilation(CompilationAnalysisContext context)
{
}
}
public MockDiagnosticAnalyzerTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new MockDiagnosticAnalyzer(), null);
private async Task VerifyDiagnosticsAsync(
string source,
params DiagnosticDescription[] expectedDiagnostics)
{
using var workspace = TestWorkspace.CreateCSharp(source, composition: GetComposition());
var actualDiagnostics = await this.GetDiagnosticsAsync(workspace, new TestParameters());
actualDiagnostics.Verify(expectedDiagnostics);
}
[WorkItem(906919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/906919")]
[Fact]
public async Task Bug906919()
{
var source = "[|class C { }|]";
await VerifyDiagnosticsAsync(source);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.Builder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
internal abstract partial class CommonObjectFormatter
{
private sealed class Builder
{
private readonly StringBuilder _sb;
private readonly bool _suppressEllipsis;
private readonly BuilderOptions _options;
private int _currentLimit;
public Builder(BuilderOptions options, bool suppressEllipsis)
{
_sb = new StringBuilder();
_suppressEllipsis = suppressEllipsis;
_options = options;
_currentLimit = Math.Min(_options.MaximumLineLength, _options.MaximumOutputLength);
}
public int Remaining
{
get { return _options.MaximumOutputLength - _sb.Length; }
}
// can be negative (the min value is -Ellipsis.Length - 1)
private int CurrentRemaining
{
get { return _currentLimit - _sb.Length; }
}
public void AppendLine()
{
// remove line length limit so that we can insert a new line even
// if the previous one hit maxed out the line limit:
_currentLimit = _options.MaximumOutputLength;
Append(_options.NewLine);
// recalc limit for the next line:
_currentLimit = (int)Math.Min((long)_sb.Length + _options.MaximumLineLength, _options.MaximumOutputLength);
}
private void AppendEllipsis()
{
if (_suppressEllipsis)
{
return;
}
var ellipsis = _options.Ellipsis;
if (string.IsNullOrEmpty(ellipsis))
{
return;
}
_sb.Append(ellipsis);
}
public void Append(char c, int count = 1)
{
if (CurrentRemaining < 0)
{
return;
}
int length = Math.Min(count, CurrentRemaining);
_sb.Append(c, length);
if (!_suppressEllipsis && length < count)
{
AppendEllipsis();
}
}
public void Append(string str, int start = 0, int count = Int32.MaxValue)
{
if (str == null || CurrentRemaining < 0)
{
return;
}
count = Math.Min(count, str.Length - start);
int length = Math.Min(count, CurrentRemaining);
_sb.Append(str, start, length);
if (!_suppressEllipsis && length < count)
{
AppendEllipsis();
}
}
public void AppendFormat(string format, params object[] args)
{
Append(string.Format(format, args));
}
public void AppendGroupOpening()
{
Append('{');
}
public void AppendGroupClosing(bool inline)
{
if (inline)
{
Append(" }");
}
else
{
AppendLine();
Append('}');
AppendLine();
}
}
public void AppendCollectionItemSeparator(bool isFirst, bool inline)
{
if (isFirst)
{
if (inline)
{
Append(' ');
}
else
{
AppendLine();
}
}
else
{
if (inline)
{
Append(", ");
}
else
{
Append(',');
AppendLine();
}
}
if (!inline)
{
Append(_options.Indentation);
}
}
/// <remarks>
/// This is for conveying cyclic dependencies to the user, not for detecting them.
/// </remarks>
internal void AppendInfiniteRecursionMarker()
{
AppendGroupOpening();
AppendCollectionItemSeparator(isFirst: true, inline: true);
Append("...");
AppendGroupClosing(inline: true);
}
public override string ToString()
{
return _sb.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;
using System.Text;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Object pretty printer.
/// </summary>
internal abstract partial class CommonObjectFormatter
{
private sealed class Builder
{
private readonly StringBuilder _sb;
private readonly bool _suppressEllipsis;
private readonly BuilderOptions _options;
private int _currentLimit;
public Builder(BuilderOptions options, bool suppressEllipsis)
{
_sb = new StringBuilder();
_suppressEllipsis = suppressEllipsis;
_options = options;
_currentLimit = Math.Min(_options.MaximumLineLength, _options.MaximumOutputLength);
}
public int Remaining
{
get { return _options.MaximumOutputLength - _sb.Length; }
}
// can be negative (the min value is -Ellipsis.Length - 1)
private int CurrentRemaining
{
get { return _currentLimit - _sb.Length; }
}
public void AppendLine()
{
// remove line length limit so that we can insert a new line even
// if the previous one hit maxed out the line limit:
_currentLimit = _options.MaximumOutputLength;
Append(_options.NewLine);
// recalc limit for the next line:
_currentLimit = (int)Math.Min((long)_sb.Length + _options.MaximumLineLength, _options.MaximumOutputLength);
}
private void AppendEllipsis()
{
if (_suppressEllipsis)
{
return;
}
var ellipsis = _options.Ellipsis;
if (string.IsNullOrEmpty(ellipsis))
{
return;
}
_sb.Append(ellipsis);
}
public void Append(char c, int count = 1)
{
if (CurrentRemaining < 0)
{
return;
}
int length = Math.Min(count, CurrentRemaining);
_sb.Append(c, length);
if (!_suppressEllipsis && length < count)
{
AppendEllipsis();
}
}
public void Append(string str, int start = 0, int count = Int32.MaxValue)
{
if (str == null || CurrentRemaining < 0)
{
return;
}
count = Math.Min(count, str.Length - start);
int length = Math.Min(count, CurrentRemaining);
_sb.Append(str, start, length);
if (!_suppressEllipsis && length < count)
{
AppendEllipsis();
}
}
public void AppendFormat(string format, params object[] args)
{
Append(string.Format(format, args));
}
public void AppendGroupOpening()
{
Append('{');
}
public void AppendGroupClosing(bool inline)
{
if (inline)
{
Append(" }");
}
else
{
AppendLine();
Append('}');
AppendLine();
}
}
public void AppendCollectionItemSeparator(bool isFirst, bool inline)
{
if (isFirst)
{
if (inline)
{
Append(' ');
}
else
{
AppendLine();
}
}
else
{
if (inline)
{
Append(", ");
}
else
{
Append(',');
AppendLine();
}
}
if (!inline)
{
Append(_options.Indentation);
}
}
/// <remarks>
/// This is for conveying cyclic dependencies to the user, not for detecting them.
/// </remarks>
internal void AppendInfiniteRecursionMarker()
{
AppendGroupOpening();
AppendCollectionItemSeparator(isFirst: true, inline: true);
Append("...");
AppendGroupClosing(inline: true);
}
public override string ToString()
{
return _sb.ToString();
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Portable/Symbols/Source/ImplicitNamedTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents implicit, script and submission classes.
/// </summary>
internal sealed class ImplicitNamedTypeSymbol : SourceMemberContainerTypeSymbol
{
internal ImplicitNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics)
: base(containingSymbol, declaration, diagnostics)
{
Debug.Assert(declaration.Kind == DeclarationKind.ImplicitClass ||
declaration.Kind == DeclarationKind.Submission ||
declaration.Kind == DeclarationKind.Script);
state.NotePartComplete(CompletionPart.EnumUnderlyingType); // No work to do for this.
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw ExceptionUtilities.Unreachable;
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
state.NotePartComplete(CompletionPart.Attributes);
return ImmutableArray<CSharpAttributeData>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base)
{
// A script class may implement interfaces in hosted scenarios.
// The interface definitions are specified via API, not in compilation source.
return NoLocation.Singleton;
}
/// <summary>
/// Returns null for a submission class.
/// This ensures that a submission class does not inherit methods such as ToString or GetHashCode.
/// </summary>
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
=> IsScriptClass ? null : this.DeclaringCompilation.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object);
protected override void CheckBase(BindingDiagnosticBag diagnostics)
{
// check that System.Object is available.
// Although submission semantically doesn't have a base class we need to emit one.
diagnostics.ReportUseSite(this.DeclaringCompilation.GetSpecialType(SpecialType.System_Object), Locations[0]);
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return BaseTypeNoUseSiteDiagnostics;
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
protected override void CheckInterfaces(BindingDiagnosticBag diagnostics)
{
// nop
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return ImmutableArray<TypeWithAnnotations>.Empty; }
}
public sealed override bool AreLocalsZeroed
{
get { return ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed; }
}
internal override bool IsComImport
{
get { return false; }
}
internal override NamedTypeSymbol ComImportCoClass
{
get { return null; }
}
internal override bool HasSpecialName
{
get { return false; }
}
internal override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal sealed override bool IsWindowsRuntimeImport
{
get { return false; }
}
public sealed override bool IsSerializable
{
get { return false; }
}
internal sealed override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal bool HasStructLayoutAttribute
{
get { return false; }
}
internal override CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
internal sealed override bool HasDeclarativeSecurity
{
get { return false; }
}
internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents implicit, script and submission classes.
/// </summary>
internal sealed class ImplicitNamedTypeSymbol : SourceMemberContainerTypeSymbol
{
internal ImplicitNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics)
: base(containingSymbol, declaration, diagnostics)
{
Debug.Assert(declaration.Kind == DeclarationKind.ImplicitClass ||
declaration.Kind == DeclarationKind.Submission ||
declaration.Kind == DeclarationKind.Script);
state.NotePartComplete(CompletionPart.EnumUnderlyingType); // No work to do for this.
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw ExceptionUtilities.Unreachable;
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
state.NotePartComplete(CompletionPart.Attributes);
return ImmutableArray<CSharpAttributeData>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base)
{
// A script class may implement interfaces in hosted scenarios.
// The interface definitions are specified via API, not in compilation source.
return NoLocation.Singleton;
}
/// <summary>
/// Returns null for a submission class.
/// This ensures that a submission class does not inherit methods such as ToString or GetHashCode.
/// </summary>
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
=> IsScriptClass ? null : this.DeclaringCompilation.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object);
protected override void CheckBase(BindingDiagnosticBag diagnostics)
{
// check that System.Object is available.
// Although submission semantically doesn't have a base class we need to emit one.
diagnostics.ReportUseSite(this.DeclaringCompilation.GetSpecialType(SpecialType.System_Object), Locations[0]);
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return BaseTypeNoUseSiteDiagnostics;
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
protected override void CheckInterfaces(BindingDiagnosticBag diagnostics)
{
// nop
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return ImmutableArray<TypeWithAnnotations>.Empty; }
}
public sealed override bool AreLocalsZeroed
{
get { return ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed; }
}
internal override bool IsComImport
{
get { return false; }
}
internal override NamedTypeSymbol ComImportCoClass
{
get { return null; }
}
internal override bool HasSpecialName
{
get { return false; }
}
internal override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal sealed override bool IsWindowsRuntimeImport
{
get { return false; }
}
public sealed override bool IsSerializable
{
get { return false; }
}
internal sealed override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal bool HasStructLayoutAttribute
{
get { return false; }
}
internal override CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
internal sealed override bool HasDeclarativeSecurity
{
get { return false; }
}
internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundUnstructuredExceptionHandlingCatchFilter.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 BoundUnstructuredExceptionHandlingCatchFilter
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Me.Type.IsBooleanType())
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 BoundUnstructuredExceptionHandlingCatchFilter
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Me.Type.IsBooleanType())
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments
{
internal abstract class AbstractDocumentationCommentCommandHandler :
IChainedCommandHandler<TypeCharCommandArgs>,
ICommandHandler<ReturnKeyCommandArgs>,
ICommandHandler<InsertCommentCommandArgs>,
IChainedCommandHandler<OpenLineAboveCommandArgs>,
IChainedCommandHandler<OpenLineBelowCommandArgs>
{
private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected AbstractDocumentationCommentCommandHandler(
IUIThreadOperationExecutor uiThreadOperationExecutor,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
Contract.ThrowIfNull(uiThreadOperationExecutor);
Contract.ThrowIfNull(undoHistoryRegistry);
Contract.ThrowIfNull(editorOperationsFactoryService);
_uiThreadOperationExecutor = uiThreadOperationExecutor;
_undoHistoryRegistry = undoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected abstract string ExteriorTriviaText { get; }
private char TriggerCharacter
{
get { return ExteriorTriviaText[^1]; }
}
public string DisplayName => EditorFeaturesResources.Documentation_Comment;
private static DocumentationCommentSnippet? InsertOnCharacterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnCharacterTyped(syntaxTree, text, position, options, cancellationToken);
private static DocumentationCommentSnippet? InsertOnEnterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnEnterTyped(syntaxTree, text, position, options, cancellationToken);
private static DocumentationCommentSnippet? InsertOnCommandInvoke(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnCommandInvoke(syntaxTree, text, position, options, cancellationToken);
private static void ApplySnippet(DocumentationCommentSnippet snippet, ITextBuffer subjectBuffer, ITextView textView)
{
var replaceSpan = snippet.SpanToReplace.ToSpan();
subjectBuffer.Replace(replaceSpan, snippet.SnippetText);
textView.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + snippet.CaretOffset));
}
private static bool CompleteComment(
ITextBuffer subjectBuffer,
ITextView textView,
Func<IDocumentationCommentSnippetService, SyntaxTree, SourceText, int, DocumentOptionSet, CancellationToken, DocumentationCommentSnippet?> getSnippetAction,
CancellationToken cancellationToken)
{
var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
return false;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var text = syntaxTree.GetText(cancellationToken);
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var snippet = getSnippetAction(service, syntaxTree, text, caretPosition, documentOptions, cancellationToken);
if (snippet != null)
{
ApplySnippet(snippet, subjectBuffer, textView);
return true;
}
return false;
}
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Ensure the character is actually typed in the editor
nextHandler();
if (args.TypedChar != TriggerCharacter)
{
return;
}
// Don't execute in cloud environment, as we let LSP handle that
if (args.SubjectBuffer.IsInLspEditorContext())
{
return;
}
CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCharacterTyped, CancellationToken.None);
}
public CommandState GetCommandState(ReturnKeyCommandArgs args)
=> CommandState.Unspecified;
public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context)
{
// Don't execute in cloud environment, as we let LSP handle that
if (args.SubjectBuffer.IsInLspEditorContext())
{
return false;
}
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var originalPosition = -1;
// The original position should be a position that is consistent with the syntax tree, even
// after Enter is pressed. Thus, we use the start of the first selection if there is one.
// Otherwise, getting the tokens to the right or the left might return unexpected results.
if (args.TextView.Selection.SelectedSpans.Count > 0)
{
var selectedSpan = args.TextView.Selection
.GetSnapshotSpansOnBuffer(args.SubjectBuffer)
.FirstOrNull();
originalPosition = selectedSpan != null
? selectedSpan.Value.Start
: args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1;
}
if (originalPosition < 0)
{
return false;
}
if (!CurrentLineStartsWithExteriorTrivia(args.SubjectBuffer, originalPosition))
{
return false;
}
// According to JasonMal, the text undo history is associated with the surface buffer
// in projection buffer scenarios, so the following line's usage of the surface buffer
// is correct.
using (var transaction = _undoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line))
{
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(args.TextView);
editorOperations.InsertNewLine();
CompleteComment(args.SubjectBuffer, args.TextView, InsertOnEnterTyped, CancellationToken.None);
// Since we're wrapping the ENTER key undo transaction, we always complete
// the transaction -- even if we didn't generate anything.
transaction.Complete();
}
return true;
}
public CommandState GetCommandState(InsertCommentCommandArgs args)
{
var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1;
if (caretPosition < 0)
{
return CommandState.Unavailable;
}
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return CommandState.Unavailable;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
var isValidTargetMember = false;
_uiThreadOperationExecutor.Execute("IntelliSense", defaultDescription: "", allowCancellation: true, showProgress: false, action: c =>
{
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(c.UserCancellationToken);
var text = syntaxTree.GetText(c.UserCancellationToken);
isValidTargetMember = service.IsValidTargetMember(syntaxTree, text, caretPosition, c.UserCancellationToken);
});
return isValidTargetMember
? CommandState.Available
: CommandState.Unavailable;
}
public bool ExecuteCommand(InsertCommentCommandArgs args, CommandExecutionContext context)
{
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Inserting_documentation_comment))
{
return CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCommandInvoke, context.OperationContext.UserCancellationToken);
}
}
public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var subjectBuffer = args.SubjectBuffer;
var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
nextHandler();
return;
}
if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition))
{
nextHandler();
return;
}
// Allow nextHandler() to run and then insert exterior trivia if necessary.
nextHandler();
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer);
}
public CommandState GetCommandState(OpenLineBelowCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var subjectBuffer = args.SubjectBuffer;
var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
nextHandler();
return;
}
if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition))
{
nextHandler();
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
// Allow nextHandler() to run and the insert exterior trivia if necessary.
nextHandler();
InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer);
}
private void InsertExteriorTriviaIfNeeded(IDocumentationCommentSnippetService service, ITextView textView, ITextBuffer subjectBuffer)
{
var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var text = document
.GetTextAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
// We only insert exterior trivia if the current line does not start with exterior trivia
// and the previous line does.
var currentLine = text.Lines.GetLineFromPosition(caretPosition);
if (currentLine.LineNumber <= 0)
{
return;
}
var previousLine = text.Lines[currentLine.LineNumber - 1];
if (LineStartsWithExteriorTrivia(currentLine) || !LineStartsWithExteriorTrivia(previousLine))
{
return;
}
var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var snippet = service.GetDocumentationCommentSnippetFromPreviousLine(documentOptions, currentLine, previousLine);
if (snippet != null)
{
ApplySnippet(snippet, subjectBuffer, textView);
}
}
private bool CurrentLineStartsWithExteriorTrivia(ITextBuffer subjectBuffer, int position)
{
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var text = document
.GetTextAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
var currentLine = text.Lines.GetLineFromPosition(position);
return LineStartsWithExteriorTrivia(currentLine);
}
private bool LineStartsWithExteriorTrivia(TextLine line)
{
var lineText = line.ToString();
var lineOffset = lineText.GetFirstNonWhitespaceOffset() ?? -1;
if (lineOffset < 0)
{
return false;
}
return string.CompareOrdinal(lineText, lineOffset, ExteriorTriviaText, 0, ExteriorTriviaText.Length) == 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments
{
internal abstract class AbstractDocumentationCommentCommandHandler :
IChainedCommandHandler<TypeCharCommandArgs>,
ICommandHandler<ReturnKeyCommandArgs>,
ICommandHandler<InsertCommentCommandArgs>,
IChainedCommandHandler<OpenLineAboveCommandArgs>,
IChainedCommandHandler<OpenLineBelowCommandArgs>
{
private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected AbstractDocumentationCommentCommandHandler(
IUIThreadOperationExecutor uiThreadOperationExecutor,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
Contract.ThrowIfNull(uiThreadOperationExecutor);
Contract.ThrowIfNull(undoHistoryRegistry);
Contract.ThrowIfNull(editorOperationsFactoryService);
_uiThreadOperationExecutor = uiThreadOperationExecutor;
_undoHistoryRegistry = undoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected abstract string ExteriorTriviaText { get; }
private char TriggerCharacter
{
get { return ExteriorTriviaText[^1]; }
}
public string DisplayName => EditorFeaturesResources.Documentation_Comment;
private static DocumentationCommentSnippet? InsertOnCharacterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnCharacterTyped(syntaxTree, text, position, options, cancellationToken);
private static DocumentationCommentSnippet? InsertOnEnterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnEnterTyped(syntaxTree, text, position, options, cancellationToken);
private static DocumentationCommentSnippet? InsertOnCommandInvoke(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken)
=> service.GetDocumentationCommentSnippetOnCommandInvoke(syntaxTree, text, position, options, cancellationToken);
private static void ApplySnippet(DocumentationCommentSnippet snippet, ITextBuffer subjectBuffer, ITextView textView)
{
var replaceSpan = snippet.SpanToReplace.ToSpan();
subjectBuffer.Replace(replaceSpan, snippet.SnippetText);
textView.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + snippet.CaretOffset));
}
private static bool CompleteComment(
ITextBuffer subjectBuffer,
ITextView textView,
Func<IDocumentationCommentSnippetService, SyntaxTree, SourceText, int, DocumentOptionSet, CancellationToken, DocumentationCommentSnippet?> getSnippetAction,
CancellationToken cancellationToken)
{
var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
return false;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var text = syntaxTree.GetText(cancellationToken);
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var snippet = getSnippetAction(service, syntaxTree, text, caretPosition, documentOptions, cancellationToken);
if (snippet != null)
{
ApplySnippet(snippet, subjectBuffer, textView);
return true;
}
return false;
}
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Ensure the character is actually typed in the editor
nextHandler();
if (args.TypedChar != TriggerCharacter)
{
return;
}
// Don't execute in cloud environment, as we let LSP handle that
if (args.SubjectBuffer.IsInLspEditorContext())
{
return;
}
CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCharacterTyped, CancellationToken.None);
}
public CommandState GetCommandState(ReturnKeyCommandArgs args)
=> CommandState.Unspecified;
public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context)
{
// Don't execute in cloud environment, as we let LSP handle that
if (args.SubjectBuffer.IsInLspEditorContext())
{
return false;
}
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var originalPosition = -1;
// The original position should be a position that is consistent with the syntax tree, even
// after Enter is pressed. Thus, we use the start of the first selection if there is one.
// Otherwise, getting the tokens to the right or the left might return unexpected results.
if (args.TextView.Selection.SelectedSpans.Count > 0)
{
var selectedSpan = args.TextView.Selection
.GetSnapshotSpansOnBuffer(args.SubjectBuffer)
.FirstOrNull();
originalPosition = selectedSpan != null
? selectedSpan.Value.Start
: args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1;
}
if (originalPosition < 0)
{
return false;
}
if (!CurrentLineStartsWithExteriorTrivia(args.SubjectBuffer, originalPosition))
{
return false;
}
// According to JasonMal, the text undo history is associated with the surface buffer
// in projection buffer scenarios, so the following line's usage of the surface buffer
// is correct.
using (var transaction = _undoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line))
{
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(args.TextView);
editorOperations.InsertNewLine();
CompleteComment(args.SubjectBuffer, args.TextView, InsertOnEnterTyped, CancellationToken.None);
// Since we're wrapping the ENTER key undo transaction, we always complete
// the transaction -- even if we didn't generate anything.
transaction.Complete();
}
return true;
}
public CommandState GetCommandState(InsertCommentCommandArgs args)
{
var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1;
if (caretPosition < 0)
{
return CommandState.Unavailable;
}
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return CommandState.Unavailable;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
var isValidTargetMember = false;
_uiThreadOperationExecutor.Execute("IntelliSense", defaultDescription: "", allowCancellation: true, showProgress: false, action: c =>
{
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(c.UserCancellationToken);
var text = syntaxTree.GetText(c.UserCancellationToken);
isValidTargetMember = service.IsValidTargetMember(syntaxTree, text, caretPosition, c.UserCancellationToken);
});
return isValidTargetMember
? CommandState.Available
: CommandState.Unavailable;
}
public bool ExecuteCommand(InsertCommentCommandArgs args, CommandExecutionContext context)
{
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Inserting_documentation_comment))
{
return CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCommandInvoke, context.OperationContext.UserCancellationToken);
}
}
public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var subjectBuffer = args.SubjectBuffer;
var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
nextHandler();
return;
}
if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition))
{
nextHandler();
return;
}
// Allow nextHandler() to run and then insert exterior trivia if necessary.
nextHandler();
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer);
}
public CommandState GetCommandState(OpenLineBelowCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Check to see if the current line starts with exterior trivia. If so, we'll take over.
// If not, let the nextHandler run.
var subjectBuffer = args.SubjectBuffer;
var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
nextHandler();
return;
}
if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition))
{
nextHandler();
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>();
// Allow nextHandler() to run and the insert exterior trivia if necessary.
nextHandler();
InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer);
}
private void InsertExteriorTriviaIfNeeded(IDocumentationCommentSnippetService service, ITextView textView, ITextBuffer subjectBuffer)
{
var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1;
if (caretPosition < 0)
{
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var text = document
.GetTextAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
// We only insert exterior trivia if the current line does not start with exterior trivia
// and the previous line does.
var currentLine = text.Lines.GetLineFromPosition(caretPosition);
if (currentLine.LineNumber <= 0)
{
return;
}
var previousLine = text.Lines[currentLine.LineNumber - 1];
if (LineStartsWithExteriorTrivia(currentLine) || !LineStartsWithExteriorTrivia(previousLine))
{
return;
}
var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var snippet = service.GetDocumentationCommentSnippetFromPreviousLine(documentOptions, currentLine, previousLine);
if (snippet != null)
{
ApplySnippet(snippet, subjectBuffer, textView);
}
}
private bool CurrentLineStartsWithExteriorTrivia(ITextBuffer subjectBuffer, int position)
{
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var text = document
.GetTextAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
var currentLine = text.Lines.GetLineFromPosition(position);
return LineStartsWithExteriorTrivia(currentLine);
}
private bool LineStartsWithExteriorTrivia(TextLine line)
{
var lineText = line.ToString();
var lineOffset = lineText.GetFirstNonWhitespaceOffset() ?? -1;
if (lineOffset < 0)
{
return false;
}
return string.CompareOrdinal(lineText, lineOffset, ExteriorTriviaText, 0, ExteriorTriviaText.Length) == 0;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/DirectiveSyntaxExtensions.DirectiveSyntaxEqualityComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal partial class DirectiveSyntaxExtensions
{
private class DirectiveSyntaxEqualityComparer : IEqualityComparer<DirectiveTriviaSyntax>
{
public static readonly DirectiveSyntaxEqualityComparer Instance = new();
private DirectiveSyntaxEqualityComparer()
{
}
public bool Equals(DirectiveTriviaSyntax x, DirectiveTriviaSyntax y)
=> x.SpanStart == y.SpanStart;
public int GetHashCode(DirectiveTriviaSyntax obj)
=> obj.SpanStart;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal partial class DirectiveSyntaxExtensions
{
private class DirectiveSyntaxEqualityComparer : IEqualityComparer<DirectiveTriviaSyntax>
{
public static readonly DirectiveSyntaxEqualityComparer Instance = new();
private DirectiveSyntaxEqualityComparer()
{
}
public bool Equals(DirectiveTriviaSyntax x, DirectiveTriviaSyntax y)
=> x.SpanStart == y.SpanStart;
public int GetHashCode(DirectiveTriviaSyntax obj)
=> obj.SpanStart;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/IProjectSystemReferenceCleanupService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService
{
/// <summary>
/// Return the set of direct Project and Package References for the given project. This
/// is used to get the initial state of the TreatAsUsed attribute for each reference.
/// </summary>
Task<ImmutableArray<ProjectSystemReferenceInfo>> GetProjectReferencesAsync(
string projectPath,
CancellationToken cancellationToken);
/// <summary>
/// Updates the project’s references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
/// <returns>True, if the reference was updated.</returns>
Task<bool> TryUpdateReferenceAsync(
string projectPath,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService
{
/// <summary>
/// Return the set of direct Project and Package References for the given project. This
/// is used to get the initial state of the TreatAsUsed attribute for each reference.
/// </summary>
Task<ImmutableArray<ProjectSystemReferenceInfo>> GetProjectReferencesAsync(
string projectPath,
CancellationToken cancellationToken);
/// <summary>
/// Updates the project’s references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
/// <returns>True, if the reference was updated.</returns>
Task<bool> TryUpdateReferenceAsync(
string projectPath,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartTokenFormatterFormatTokenTests : CSharpFormatterTestsBase
{
public SmartTokenFormatterFormatTokenTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task EmptyFile1()
{
var code = @"{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile2()
{
var code = @"}";
await ExpectException_SmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace1()
{
var code = @"namespace NS
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace2()
{
var code = @"namespace NS
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace3()
{
var code = @"namespace NS
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 2,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class1()
{
var code = @"namespace NS
{
class Class
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class2()
{
var code = @"namespace NS
{
class Class
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class3()
{
var code = @"namespace NS
{
class Class
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 4,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property1()
{
var code = @"namespace NS
{
class Class
{
int Goo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property2()
{
var code = @"namespace NS
{
class Class
{
int Goo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event1()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Goo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event2()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Goo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer1()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer2()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 6,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block4()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
var expected = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
await AssertSmartTokenFormatterOpenBraceAsync(
expected,
code,
indentationLine: 6);
}
[Fact]
[WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
int[,] arr =
{
{1,1}, {2,2}
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 9,
expectedSpace: 12);
}
[Fact]
[WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EnterWithTrailingWhitespace()
{
var code = @"class Class
{
void Method(int i)
{
var a = new {
};
";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task OpenBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
$${
}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task CloseBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
{
$$}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestPreprocessor()
{
var code = @"
class C
{
void M()
{
#
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#', useTabs: false);
Assert.Equal(0, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: '#', useTabs: true);
Assert.Equal(0, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestRegion()
{
var code = @"
class C
{
void M()
{
#region
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false);
Assert.Equal(8, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true);
Assert.Equal(8, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestEndRegion()
{
var code = @"
class C
{
void M()
{
#region
#endregion
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false);
Assert.Equal(8, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true);
Assert.Equal(8, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestSelect()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Goo()
{
return from a in new[] { 1, 2, 3 }
select
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't', useTabs: false);
Assert.Equal(15, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 't', useTabs: true);
Assert.Equal(15, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestWhere()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Goo()
{
return from a in new[] { 1, 2, 3 }
where
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e', useTabs: false);
Assert.Equal(15, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 'e', useTabs: true);
Assert.Equal(15, actualIndentation);
}
private static async Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation)
{
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false);
}
private static Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation, bool useTabs)
{
MarkupTestFile.GetPositionAndSpan(markup,
out var code, out var position, out TextSpan span);
return AssertSmartTokenFormatterOpenBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
useTabs,
baseIndentation,
span);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default)
{
await AssertSmartTokenFormatterOpenBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
bool useTabs,
int? baseIndentation,
TextSpan span)
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', useTabs, baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine)
{
await AssertSmartTokenFormatterOpenBraceAsync(expected, code, indentationLine, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceAsync(expected.Replace(" ", "\t"), code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine,
bool useTabs)
{
// create tree service
using var workspace = TestWorkspace.CreateCSharp(code);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
var buffer = workspace.Documents.First().GetTextBuffer();
var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{');
Assert.Equal(expected, actual);
}
private static async Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation)
{
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false);
}
private static Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation, bool useTabs)
{
MarkupTestFile.GetPositionAndSpan(markup,
out var code, out var position, out TextSpan span);
return AssertSmartTokenFormatterCloseBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
useTabs,
baseIndentation,
span);
}
private static async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default)
{
await AssertSmartTokenFormatterCloseBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false);
await AssertSmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
bool useTabs,
int? baseIndentation,
TextSpan span)
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs, baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine)
{
await ExpectException_SmartTokenFormatterCloseBraceAsync(code, indentationLine, useTabs: false).ConfigureAwait(false);
await ExpectException_SmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false);
}
private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
bool useTabs)
{
Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs)));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartTokenFormatterFormatTokenTests : CSharpFormatterTestsBase
{
public SmartTokenFormatterFormatTokenTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task EmptyFile1()
{
var code = @"{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile2()
{
var code = @"}";
await ExpectException_SmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace1()
{
var code = @"namespace NS
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace2()
{
var code = @"namespace NS
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace3()
{
var code = @"namespace NS
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 2,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class1()
{
var code = @"namespace NS
{
class Class
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class2()
{
var code = @"namespace NS
{
class Class
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class3()
{
var code = @"namespace NS
{
class Class
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 4,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property1()
{
var code = @"namespace NS
{
class Class
{
int Goo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property2()
{
var code = @"namespace NS
{
class Class
{
int Goo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event1()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Goo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event2()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Goo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer1()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer2()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 6,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block4()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
var expected = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
await AssertSmartTokenFormatterOpenBraceAsync(
expected,
code,
indentationLine: 6);
}
[Fact]
[WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
int[,] arr =
{
{1,1}, {2,2}
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 9,
expectedSpace: 12);
}
[Fact]
[WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EnterWithTrailingWhitespace()
{
var code = @"class Class
{
void Method(int i)
{
var a = new {
};
";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task OpenBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
$${
}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task CloseBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
{
$$}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestPreprocessor()
{
var code = @"
class C
{
void M()
{
#
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#', useTabs: false);
Assert.Equal(0, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: '#', useTabs: true);
Assert.Equal(0, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestRegion()
{
var code = @"
class C
{
void M()
{
#region
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false);
Assert.Equal(8, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true);
Assert.Equal(8, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestEndRegion()
{
var code = @"
class C
{
void M()
{
#region
#endregion
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false);
Assert.Equal(8, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true);
Assert.Equal(8, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestSelect()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Goo()
{
return from a in new[] { 1, 2, 3 }
select
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't', useTabs: false);
Assert.Equal(15, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 't', useTabs: true);
Assert.Equal(15, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestWhere()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Goo()
{
return from a in new[] { 1, 2, 3 }
where
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e', useTabs: false);
Assert.Equal(15, actualIndentation);
actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 'e', useTabs: true);
Assert.Equal(15, actualIndentation);
}
private static async Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation)
{
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false);
}
private static Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation, bool useTabs)
{
MarkupTestFile.GetPositionAndSpan(markup,
out var code, out var position, out TextSpan span);
return AssertSmartTokenFormatterOpenBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
useTabs,
baseIndentation,
span);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default)
{
await AssertSmartTokenFormatterOpenBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
bool useTabs,
int? baseIndentation,
TextSpan span)
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', useTabs, baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine)
{
await AssertSmartTokenFormatterOpenBraceAsync(expected, code, indentationLine, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterOpenBraceAsync(expected.Replace(" ", "\t"), code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine,
bool useTabs)
{
// create tree service
using var workspace = TestWorkspace.CreateCSharp(code);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
var buffer = workspace.Documents.First().GetTextBuffer();
var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{');
Assert.Equal(expected, actual);
}
private static async Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation)
{
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false);
await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false);
}
private static Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation, bool useTabs)
{
MarkupTestFile.GetPositionAndSpan(markup,
out var code, out var position, out TextSpan span);
return AssertSmartTokenFormatterCloseBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
useTabs,
baseIndentation,
span);
}
private static async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default)
{
await AssertSmartTokenFormatterCloseBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false);
await AssertSmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false);
}
private static async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
bool useTabs,
int? baseIndentation,
TextSpan span)
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs, baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine)
{
await ExpectException_SmartTokenFormatterCloseBraceAsync(code, indentationLine, useTabs: false).ConfigureAwait(false);
await ExpectException_SmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false);
}
private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
bool useTabs)
{
Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs)));
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItemKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal enum RoslynNavigationBarItemKind
{
Symbol,
GenerateDefaultConstructor,
GenerateEventHandler,
GenerateFinalizer,
GenerateMethod,
Actionless,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal enum RoslynNavigationBarItemKind
{
Symbol,
GenerateDefaultConstructor,
GenerateEventHandler,
GenerateFinalizer,
GenerateMethod,
Actionless,
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/CoreTest/WorkspaceTests/DynamicFileInfoProviderMefTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class DynamicFileInfoProviderMefTests : TestBase
{
[Fact]
public void TestFileExtensionsMetadata()
{
var lazy = GetDynamicFileInfoProvider();
Assert.Equal(2, lazy.Metadata.Extensions.Count());
AssertEx.SetEqual(new[] { "cshtml", "vbhtml" }, lazy.Metadata.Extensions);
}
[Fact]
public void TestInvalidArgument1()
{
Assert.Throws<ArgumentException>(() =>
{
new ExportDynamicFileInfoProviderAttribute();
});
}
[Fact]
public void TestInvalidArgument2()
{
Assert.Throws<ArgumentException>(() =>
{
new FileExtensionsMetadata();
});
}
internal static Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata> GetDynamicFileInfoProvider()
{
var composition = TestComposition.Empty.AddParts(typeof(TestDynamicFileInfoProviderThatProducesNoFiles));
return composition.ExportProviderFactory.CreateExportProvider().GetExport<IDynamicFileInfoProvider, FileExtensionsMetadata>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class DynamicFileInfoProviderMefTests : TestBase
{
[Fact]
public void TestFileExtensionsMetadata()
{
var lazy = GetDynamicFileInfoProvider();
Assert.Equal(2, lazy.Metadata.Extensions.Count());
AssertEx.SetEqual(new[] { "cshtml", "vbhtml" }, lazy.Metadata.Extensions);
}
[Fact]
public void TestInvalidArgument1()
{
Assert.Throws<ArgumentException>(() =>
{
new ExportDynamicFileInfoProviderAttribute();
});
}
[Fact]
public void TestInvalidArgument2()
{
Assert.Throws<ArgumentException>(() =>
{
new FileExtensionsMetadata();
});
}
internal static Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata> GetDynamicFileInfoProvider()
{
var composition = TestComposition.Empty.AddParts(typeof(TestDynamicFileInfoProviderThatProducesNoFiles));
return composition.ExportProviderFactory.CreateExportProvider().GetExport<IDynamicFileInfoProvider, FileExtensionsMetadata>();
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/Core/Test/Progression/GraphNodeIdTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class GraphNodeIdTests
Private Async Function AssertMarkedNodeIdIsAsync(code As String, expectedId As String, Optional language As String = "C#", Optional symbolTransform As Func(Of ISymbol, ISymbol) = Nothing) As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language=<%= language %> CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
<%= code %>
</Document>
</Project>
</Workspace>)
Dim graph = await testState.GetGraphWithMarkedSymbolNodeAsync(symbolTransform)
Dim node = graph.Nodes.Single()
Assert.Equal(expectedId, node.Id.ToString())
End Using
End Function
<WpfFact>
Public Async Function TestSimpleType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class $$C { } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C)")
End Function
<WpfFact>
Public Async Function TestNestedType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class C { class $$E { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=E ParentType=C))")
End Function
<WpfFact>
Public Async Function TestMemberWithSimpleArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=Int32))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithNestedArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[][,] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=(Name=Int32 ArrayRank=2 ParentType=Int32)))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { struct S { } unsafe void $$M(S** p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=S Indirection=2 ParentType=C))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithVoidPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { unsafe void $$M(void* p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Void Indirection=1))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T t, U u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0),(ParameterIdentifier=0)]))")
End Function
<WpfFact, WorkItem(547263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547263")>
Public Async Function TestMemberWithParameterTypeConstructedWithMemberTypeParameter() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M<T>(T t, System.Func<T, int> u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithArraysOfGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[] t, U[] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ParameterIdentifier=0)))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithArraysOfGenericTypeParameters2() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[][,] t, U[][,] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0)))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(ParameterIdentifier=0))))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithGenericType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<int> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=Object)]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithGenericTypeOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<dynamic> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Namespace=System Type=Object)]))]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithArrayOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic[] d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=(Name=Object ArrayRank=1 ParentType=Object))]))")
End Function
<WpfFact, WorkItem(547234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547234")>
Public Async Function TestErrorType() As Task
Await AssertMarkedNodeIdIsAsync(
"Class $$C : Inherits D : End Class",
"Type=D",
LanguageNames.VisualBasic,
Function(s) DirectCast(s, INamedTypeSymbol).BaseType)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class GraphNodeIdTests
Private Async Function AssertMarkedNodeIdIsAsync(code As String, expectedId As String, Optional language As String = "C#", Optional symbolTransform As Func(Of ISymbol, ISymbol) = Nothing) As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language=<%= language %> CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
<%= code %>
</Document>
</Project>
</Workspace>)
Dim graph = await testState.GetGraphWithMarkedSymbolNodeAsync(symbolTransform)
Dim node = graph.Nodes.Single()
Assert.Equal(expectedId, node.Id.ToString())
End Using
End Function
<WpfFact>
Public Async Function TestSimpleType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class $$C { } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C)")
End Function
<WpfFact>
Public Async Function TestNestedType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class C { class $$E { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=E ParentType=C))")
End Function
<WpfFact>
Public Async Function TestMemberWithSimpleArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=Int32))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithNestedArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[][,] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=(Name=Int32 ArrayRank=2 ParentType=Int32)))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { struct S { } unsafe void $$M(S** p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=S Indirection=2 ParentType=C))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithVoidPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { unsafe void $$M(void* p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Void Indirection=1))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T t, U u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0),(ParameterIdentifier=0)]))")
End Function
<WpfFact, WorkItem(547263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547263")>
Public Async Function TestMemberWithParameterTypeConstructedWithMemberTypeParameter() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M<T>(T t, System.Func<T, int> u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithArraysOfGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[] t, U[] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ParameterIdentifier=0)))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithArraysOfGenericTypeParameters2() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[][,] t, U[][,] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0)))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(ParameterIdentifier=0))))]))")
End Function
<WpfFact>
Public Async Function TestMemberWithGenericType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<int> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=Object)]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithGenericTypeOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<dynamic> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Namespace=System Type=Object)]))]))")
End Function
<WpfFact, WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithArrayOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic[] d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=(Name=Object ArrayRank=1 ParentType=Object))]))")
End Function
<WpfFact, WorkItem(547234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547234")>
Public Async Function TestErrorType() As Task
Await AssertMarkedNodeIdIsAsync(
"Class $$C : Inherits D : End Class",
"Type=D",
LanguageNames.VisualBasic,
Function(s) DirectCast(s, INamedTypeSymbol).BaseType)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int a = 1)
{
M();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int x, int a = 1)
{
M(1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x = 2)
{
M()
M(2);
M(x: 2);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, int x = 2)
{
M()
M(x: 2);
M(x: 2);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(params int[] p)
{
M();
M(1);
M(1, 2);
M(1, 2, 3);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, params int[] p)
{
M();
M(p: new int[] { 1 });
M(p: new int[] { 1, 2 });
M(p: new int[] { 1, 2, 3 });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor()
{
var markup = @"
[Some(1, 2, 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute$$(int a, int b, int y = 4)
{
}
}";
var permutation = new[] {
new AddedParameterOrExistingIndex(0),
new AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"),
new AddedParameterOrExistingIndex(2)};
var updatedCode = @"
[Some(1, 2, y: 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute(int a, int b, int x = 3, int y = 4)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int a = 1)
{
M();
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") };
var updatedCode = @"
class C
{
void M(int x, int a = 1)
{
M(1);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(int x = 2)
{
M()
M(2);
M(x: 2);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, int x = 2)
{
M()
M(x: 2);
M(x: 2);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted()
{
var markup = @"
class C
{
void M$$(params int[] p)
{
M();
M(1);
M(1, 2);
M(1, 2, 3);
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"),
new AddedParameterOrExistingIndex(0) };
var updatedCode = @"
class C
{
void M(int a = 1, params int[] p)
{
M();
M(p: new int[] { 1 });
M(p: new int[] { 1, 2 });
M(p: new int[] { 1, 2, 3 });
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor()
{
var markup = @"
[Some(1, 2, 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute$$(int a, int b, int y = 4)
{
}
}";
var permutation = new[] {
new AddedParameterOrExistingIndex(0),
new AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"),
new AddedParameterOrExistingIndex(2)};
var updatedCode = @"
[Some(1, 2, y: 4)]
class SomeAttribute : System.Attribute
{
public SomeAttribute(int a, int b, int x = 3, int y = 4)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CompletionProviderOrderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
[UseExportProvider]
public class CompletionProviderOrderTests
{
/// <summary>
/// Verifies the exact order of all built-in completion providers.
/// </summary>
[Fact]
public void TestCompletionProviderOrder()
{
var exportProvider = EditorTestCompositions.EditorFeaturesWpf.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var actualOrder = orderedCSharpCompletionProviders.Select(x => x.Value.GetType()).ToArray();
var expectedOrder = new[]
{
// Marker for start of built-in completion providers
typeof(FirstBuiltInCompletionProvider),
// Built-in providers
typeof(AttributeNamedParameterCompletionProvider),
typeof(NamedParameterCompletionProvider),
typeof(KeywordCompletionProvider),
typeof(AwaitCompletionProvider),
typeof(SpeculativeTCompletionProvider),
typeof(SymbolCompletionProvider),
typeof(UnnamedSymbolCompletionProvider),
typeof(ExplicitInterfaceMemberCompletionProvider),
typeof(ExplicitInterfaceTypeCompletionProvider),
typeof(ObjectCreationCompletionProvider),
typeof(ObjectAndWithInitializerCompletionProvider),
typeof(CSharpSuggestionModeCompletionProvider),
typeof(EnumAndCompletionListTagCompletionProvider),
typeof(CrefCompletionProvider),
typeof(SnippetCompletionProvider),
typeof(ExternAliasCompletionProvider),
typeof(PreprocessorCompletionProvider),
typeof(OverrideCompletionProvider),
typeof(PartialMethodCompletionProvider),
typeof(PartialTypeCompletionProvider),
typeof(XmlDocCommentCompletionProvider),
typeof(TupleNameCompletionProvider),
typeof(DeclarationNameCompletionProvider),
typeof(InternalsVisibleToCompletionProvider),
typeof(PropertySubpatternCompletionProvider),
typeof(TypeImportCompletionProvider),
typeof(ExtensionMethodImportCompletionProvider),
typeof(EmbeddedLanguageCompletionProvider),
typeof(FunctionPointerUnmanagedCallingConventionCompletionProvider),
// Built-in interactive providers
typeof(LoadDirectiveCompletionProvider),
typeof(ReferenceDirectiveCompletionProvider),
// Marker for end of built-in completion providers
typeof(LastBuiltInCompletionProvider),
};
AssertEx.EqualOrDiff(
string.Join(Environment.NewLine, expectedOrder.Select(x => x.FullName)),
string.Join(Environment.NewLine, actualOrder.Select(x => x.FullName)));
}
/// <summary>
/// Verifies that the order of built-in completion providers is deterministic.
/// </summary>
/// <remarks>We ensure that the order is deterministic by the list being explicit: each provider except the first must have
/// a Before or After attribute that explicitly orders it by the next one in the list. This ensures that if more than
/// one provider provides the same completion item, the provider that provides the winning one is consistent.</remarks>
[Fact]
public void TestCompletionProviderOrderMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
for (var i = 0; i < orderedCSharpCompletionProviders.Count; i++)
{
if (i == 0)
{
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped);
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.AfterTyped);
}
else if (i == orderedCSharpCompletionProviders.Count - 1) // last one
{
// The last one isn't before anything else
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped);
// The last completion marker should be last; this is ensured by either the last "real" provider saying it comes before the
// marker, or the last completion marker comes after the last "real" provider.
if (!orderedCSharpCompletionProviders[i].Metadata.AfterTyped.Contains(orderedCSharpCompletionProviders[i - 1].Metadata.Name))
{
// Make sure the last built-in provider comes before the marker
Assert.Contains(orderedCSharpCompletionProviders[i].Metadata.Name, orderedCSharpCompletionProviders[i - 1].Metadata.BeforeTyped);
}
}
else
{
if (orderedCSharpCompletionProviders[i].Metadata.BeforeTyped.Any())
{
Assert.Equal(orderedCSharpCompletionProviders.Last().Metadata.Name, Assert.Single(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped));
}
var after = Assert.Single(orderedCSharpCompletionProviders[i].Metadata.AfterTyped);
Assert.Equal(orderedCSharpCompletionProviders[i - 1].Metadata.Name, after);
}
}
}
[Fact]
public void TestCompletionProviderFirstNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var firstCompletionProvider = orderedCSharpCompletionProviders.First();
Assert.Equal("FirstBuiltInCompletionProvider", firstCompletionProvider.Metadata.Name);
}
[Fact]
public void TestCompletionProviderLastNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var lastCompletionProvider = orderedCSharpCompletionProviders.Last();
Assert.Equal("LastBuiltInCompletionProvider", lastCompletionProvider.Metadata.Name);
}
[Fact]
public void TestCompletionProviderNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var csharpCompletionProviders = completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp);
foreach (var export in csharpCompletionProviders)
{
Assert.Equal(export.Value.GetType().Name, export.Metadata.Name);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
[UseExportProvider]
public class CompletionProviderOrderTests
{
/// <summary>
/// Verifies the exact order of all built-in completion providers.
/// </summary>
[Fact]
public void TestCompletionProviderOrder()
{
var exportProvider = EditorTestCompositions.EditorFeaturesWpf.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var actualOrder = orderedCSharpCompletionProviders.Select(x => x.Value.GetType()).ToArray();
var expectedOrder = new[]
{
// Marker for start of built-in completion providers
typeof(FirstBuiltInCompletionProvider),
// Built-in providers
typeof(AttributeNamedParameterCompletionProvider),
typeof(NamedParameterCompletionProvider),
typeof(KeywordCompletionProvider),
typeof(AwaitCompletionProvider),
typeof(SpeculativeTCompletionProvider),
typeof(SymbolCompletionProvider),
typeof(UnnamedSymbolCompletionProvider),
typeof(ExplicitInterfaceMemberCompletionProvider),
typeof(ExplicitInterfaceTypeCompletionProvider),
typeof(ObjectCreationCompletionProvider),
typeof(ObjectAndWithInitializerCompletionProvider),
typeof(CSharpSuggestionModeCompletionProvider),
typeof(EnumAndCompletionListTagCompletionProvider),
typeof(CrefCompletionProvider),
typeof(SnippetCompletionProvider),
typeof(ExternAliasCompletionProvider),
typeof(PreprocessorCompletionProvider),
typeof(OverrideCompletionProvider),
typeof(PartialMethodCompletionProvider),
typeof(PartialTypeCompletionProvider),
typeof(XmlDocCommentCompletionProvider),
typeof(TupleNameCompletionProvider),
typeof(DeclarationNameCompletionProvider),
typeof(InternalsVisibleToCompletionProvider),
typeof(PropertySubpatternCompletionProvider),
typeof(TypeImportCompletionProvider),
typeof(ExtensionMethodImportCompletionProvider),
typeof(EmbeddedLanguageCompletionProvider),
typeof(FunctionPointerUnmanagedCallingConventionCompletionProvider),
// Built-in interactive providers
typeof(LoadDirectiveCompletionProvider),
typeof(ReferenceDirectiveCompletionProvider),
// Marker for end of built-in completion providers
typeof(LastBuiltInCompletionProvider),
};
AssertEx.EqualOrDiff(
string.Join(Environment.NewLine, expectedOrder.Select(x => x.FullName)),
string.Join(Environment.NewLine, actualOrder.Select(x => x.FullName)));
}
/// <summary>
/// Verifies that the order of built-in completion providers is deterministic.
/// </summary>
/// <remarks>We ensure that the order is deterministic by the list being explicit: each provider except the first must have
/// a Before or After attribute that explicitly orders it by the next one in the list. This ensures that if more than
/// one provider provides the same completion item, the provider that provides the winning one is consistent.</remarks>
[Fact]
public void TestCompletionProviderOrderMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
for (var i = 0; i < orderedCSharpCompletionProviders.Count; i++)
{
if (i == 0)
{
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped);
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.AfterTyped);
}
else if (i == orderedCSharpCompletionProviders.Count - 1) // last one
{
// The last one isn't before anything else
Assert.Empty(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped);
// The last completion marker should be last; this is ensured by either the last "real" provider saying it comes before the
// marker, or the last completion marker comes after the last "real" provider.
if (!orderedCSharpCompletionProviders[i].Metadata.AfterTyped.Contains(orderedCSharpCompletionProviders[i - 1].Metadata.Name))
{
// Make sure the last built-in provider comes before the marker
Assert.Contains(orderedCSharpCompletionProviders[i].Metadata.Name, orderedCSharpCompletionProviders[i - 1].Metadata.BeforeTyped);
}
}
else
{
if (orderedCSharpCompletionProviders[i].Metadata.BeforeTyped.Any())
{
Assert.Equal(orderedCSharpCompletionProviders.Last().Metadata.Name, Assert.Single(orderedCSharpCompletionProviders[i].Metadata.BeforeTyped));
}
var after = Assert.Single(orderedCSharpCompletionProviders[i].Metadata.AfterTyped);
Assert.Equal(orderedCSharpCompletionProviders[i - 1].Metadata.Name, after);
}
}
}
[Fact]
public void TestCompletionProviderFirstNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var firstCompletionProvider = orderedCSharpCompletionProviders.First();
Assert.Equal("FirstBuiltInCompletionProvider", firstCompletionProvider.Metadata.Name);
}
[Fact]
public void TestCompletionProviderLastNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var orderedCSharpCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp));
var lastCompletionProvider = orderedCSharpCompletionProviders.Last();
Assert.Equal("LastBuiltInCompletionProvider", lastCompletionProvider.Metadata.Name);
}
[Fact]
public void TestCompletionProviderNameMetadata()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var completionProviderExports = exportProvider.GetExports<CompletionProvider, CompletionProviderMetadata>();
var csharpCompletionProviders = completionProviderExports.Where(export => export.Metadata.Language == LanguageNames.CSharp);
foreach (var export in csharpCompletionProviders)
{
Assert.Equal(export.Value.GetType().Name, export.Metadata.Name);
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/Core/Portable/Shared/Extensions/SafeHandleExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SafeHandleExtensions
{
/// <summary>
/// Acquires a lease on a safe handle. The lease increments the reference count of the <see cref="SafeHandle"/>
/// to ensure the handle is not released prior to the lease being released.
/// </summary>
/// <remarks>
/// This method is intended to be used in the initializer of a <c>using</c> statement. Failing to release the
/// lease will permanently prevent the underlying <see cref="SafeHandle"/> from being released by the garbage
/// collector.
/// </remarks>
/// <param name="handle">The <see cref="SafeHandle"/> to lease.</param>
/// <returns>A <see cref="SafeHandleLease"/>, which must be disposed to release the resource.</returns>
/// <exception cref="ObjectDisposedException">If the lease could not be acquired.</exception>
public static SafeHandleLease Lease(this SafeHandle handle)
{
RoslynDebug.AssertNotNull(handle);
var success = false;
try
{
handle.DangerousAddRef(ref success);
Debug.Assert(success, $"{nameof(SafeHandle.DangerousAddRef)} does not return when {nameof(success)} is false.");
return new SafeHandleLease(handle);
}
catch
{
if (success)
handle.DangerousRelease();
throw;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SafeHandleExtensions
{
/// <summary>
/// Acquires a lease on a safe handle. The lease increments the reference count of the <see cref="SafeHandle"/>
/// to ensure the handle is not released prior to the lease being released.
/// </summary>
/// <remarks>
/// This method is intended to be used in the initializer of a <c>using</c> statement. Failing to release the
/// lease will permanently prevent the underlying <see cref="SafeHandle"/> from being released by the garbage
/// collector.
/// </remarks>
/// <param name="handle">The <see cref="SafeHandle"/> to lease.</param>
/// <returns>A <see cref="SafeHandleLease"/>, which must be disposed to release the resource.</returns>
/// <exception cref="ObjectDisposedException">If the lease could not be acquired.</exception>
public static SafeHandleLease Lease(this SafeHandle handle)
{
RoslynDebug.AssertNotNull(handle);
var success = false;
try
{
handle.DangerousAddRef(ref success);
Debug.Assert(success, $"{nameof(SafeHandle.DangerousAddRef)} does not return when {nameof(success)} is false.");
return new SafeHandleLease(handle);
}
catch
{
if (success)
handle.DangerousRelease();
throw;
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Tools/AnalyzerRunner/Options.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace AnalyzerRunner
{
public sealed class Options
{
public readonly string AnalyzerPath;
public readonly string SolutionPath;
public readonly ImmutableHashSet<string> AnalyzerNames;
public readonly ImmutableHashSet<string> RefactoringNodes;
public readonly bool RunConcurrent;
public readonly bool ReportSuppressedDiagnostics;
public readonly bool ApplyChanges;
public readonly bool UseAll;
public readonly int Iterations;
// Options specific to incremental analyzers
public readonly bool UsePersistentStorage;
public readonly ImmutableArray<string> IncrementalAnalyzerNames;
public readonly bool FullSolutionAnalysis;
// Options used by AnalyzerRunner CLI only
internal readonly bool ShowStats;
internal readonly bool ShowCompilerDiagnostics;
internal readonly bool TestDocuments;
internal readonly Func<string, bool> TestDocumentMatch;
internal readonly int TestDocumentIterations;
internal readonly string LogFileName;
internal readonly string ProfileRoot;
internal BackgroundAnalysisScope AnalysisScope
=> FullSolutionAnalysis ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default;
public Options(
string analyzerPath,
string solutionPath,
ImmutableHashSet<string> analyzerIds,
ImmutableHashSet<string> refactoringNodes,
bool runConcurrent,
bool reportSuppressedDiagnostics,
bool applyChanges,
bool useAll,
int iterations,
bool usePersistentStorage,
bool fullSolutionAnalysis,
ImmutableArray<string> incrementalAnalyzerNames)
: this(analyzerPath,
solutionPath,
analyzerIds,
refactoringNodes,
runConcurrent,
reportSuppressedDiagnostics,
applyChanges,
showStats: false,
showCompilerDiagnostics: false,
useAll,
iterations,
testDocuments: false,
testDocumentMatch: _ => false,
testDocumentIterations: 0,
logFileName: null,
profileRoot: null,
usePersistentStorage,
fullSolutionAnalysis,
incrementalAnalyzerNames)
{ }
internal Options(
string analyzerPath,
string solutionPath,
ImmutableHashSet<string> analyzerIds,
ImmutableHashSet<string> refactoringNodes,
bool runConcurrent,
bool reportSuppressedDiagnostics,
bool applyChanges,
bool showStats,
bool showCompilerDiagnostics,
bool useAll,
int iterations,
bool testDocuments,
Func<string, bool> testDocumentMatch,
int testDocumentIterations,
string logFileName,
string profileRoot,
bool usePersistentStorage,
bool fullSolutionAnalysis,
ImmutableArray<string> incrementalAnalyzerNames)
{
AnalyzerPath = analyzerPath;
SolutionPath = solutionPath;
AnalyzerNames = analyzerIds;
RefactoringNodes = refactoringNodes;
RunConcurrent = runConcurrent;
ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
ApplyChanges = applyChanges;
ShowStats = showStats;
ShowCompilerDiagnostics = showCompilerDiagnostics;
UseAll = useAll;
Iterations = iterations;
TestDocuments = testDocuments;
TestDocumentMatch = testDocumentMatch;
TestDocumentIterations = testDocumentIterations;
LogFileName = logFileName;
ProfileRoot = profileRoot;
UsePersistentStorage = usePersistentStorage;
FullSolutionAnalysis = fullSolutionAnalysis;
IncrementalAnalyzerNames = incrementalAnalyzerNames;
}
internal static Options Create(string[] args)
{
string analyzerPath = null;
string solutionPath = null;
var builder = ImmutableHashSet.CreateBuilder<string>();
var refactoringBuilder = ImmutableHashSet.CreateBuilder<string>();
bool runConcurrent = false;
bool reportSuppressedDiagnostics = false;
bool applyChanges = false;
bool showStats = false;
bool showCompilerDiagnostics = false;
bool useAll = false;
int iterations = 1;
bool testDocuments = false;
Func<string, bool> testDocumentMatch = _ => true;
int testDocumentIterations = 10;
string logFileName = null;
string profileRoot = null;
var usePersistentStorage = false;
var fullSolutionAnalysis = false;
var incrementalAnalyzerNames = ImmutableArray.CreateBuilder<string>();
int i = 0;
while (i < args.Length)
{
var arg = args[i++];
string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException($"Missing value for option {arg}");
switch (arg)
{
case "/all":
useAll = true;
break;
case "/stats":
showStats = true;
break;
case "/compilerStats":
showCompilerDiagnostics = true;
break;
case "/concurrent":
runConcurrent = true;
break;
case "/editperf":
testDocuments = true;
break;
case var _ when arg.StartsWith("/editperf:"):
testDocuments = true;
var expression = new Regex(arg.Substring("/editperf:".Length), RegexOptions.Compiled | RegexOptions.IgnoreCase);
testDocumentMatch = documentPath => expression.IsMatch(documentPath);
break;
case var _ when arg.StartsWith("/edititer:"):
testDocumentIterations = int.Parse(arg.Substring("/edititer:".Length));
break;
case var _ when arg.StartsWith("/iter:"):
iterations = int.Parse(arg.Substring("/iter:".Length));
break;
case "/suppressed":
reportSuppressedDiagnostics = true;
break;
case "/apply":
applyChanges = true;
break;
case "/a":
builder.Add(ReadValue());
break;
case "/refactor":
refactoringBuilder.Add(ReadValue());
break;
case "/log":
logFileName = ReadValue();
break;
case "/profileroot":
profileRoot = ReadValue();
break;
case "/persist":
usePersistentStorage = true;
break;
case "/fsa":
fullSolutionAnalysis = true;
break;
case "/ia":
incrementalAnalyzerNames.Add(ReadValue());
break;
default:
if (analyzerPath == null)
{
analyzerPath = arg;
}
else if (solutionPath == null)
{
solutionPath = arg;
}
else
{
throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ?
"Unrecognized option " + arg :
"Unrecognized parameter " + arg));
}
break;
}
}
if (analyzerPath == null)
{
throw new InvalidDataException("Missing analyzer path");
}
if (solutionPath == null)
{
throw new InvalidDataException("Missing solution path");
}
return new Options(
analyzerPath: analyzerPath,
solutionPath: solutionPath,
analyzerIds: builder.ToImmutableHashSet(),
refactoringNodes: refactoringBuilder.ToImmutableHashSet(),
runConcurrent: runConcurrent,
reportSuppressedDiagnostics: reportSuppressedDiagnostics,
applyChanges: applyChanges,
showStats: showStats,
showCompilerDiagnostics: showCompilerDiagnostics,
useAll: useAll,
iterations: iterations,
testDocuments: testDocuments,
testDocumentMatch: testDocumentMatch,
testDocumentIterations: testDocumentIterations,
logFileName: logFileName,
profileRoot: profileRoot,
usePersistentStorage: usePersistentStorage,
fullSolutionAnalysis: fullSolutionAnalysis,
incrementalAnalyzerNames: incrementalAnalyzerNames.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 System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace AnalyzerRunner
{
public sealed class Options
{
public readonly string AnalyzerPath;
public readonly string SolutionPath;
public readonly ImmutableHashSet<string> AnalyzerNames;
public readonly ImmutableHashSet<string> RefactoringNodes;
public readonly bool RunConcurrent;
public readonly bool ReportSuppressedDiagnostics;
public readonly bool ApplyChanges;
public readonly bool UseAll;
public readonly int Iterations;
// Options specific to incremental analyzers
public readonly bool UsePersistentStorage;
public readonly ImmutableArray<string> IncrementalAnalyzerNames;
public readonly bool FullSolutionAnalysis;
// Options used by AnalyzerRunner CLI only
internal readonly bool ShowStats;
internal readonly bool ShowCompilerDiagnostics;
internal readonly bool TestDocuments;
internal readonly Func<string, bool> TestDocumentMatch;
internal readonly int TestDocumentIterations;
internal readonly string LogFileName;
internal readonly string ProfileRoot;
internal BackgroundAnalysisScope AnalysisScope
=> FullSolutionAnalysis ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default;
public Options(
string analyzerPath,
string solutionPath,
ImmutableHashSet<string> analyzerIds,
ImmutableHashSet<string> refactoringNodes,
bool runConcurrent,
bool reportSuppressedDiagnostics,
bool applyChanges,
bool useAll,
int iterations,
bool usePersistentStorage,
bool fullSolutionAnalysis,
ImmutableArray<string> incrementalAnalyzerNames)
: this(analyzerPath,
solutionPath,
analyzerIds,
refactoringNodes,
runConcurrent,
reportSuppressedDiagnostics,
applyChanges,
showStats: false,
showCompilerDiagnostics: false,
useAll,
iterations,
testDocuments: false,
testDocumentMatch: _ => false,
testDocumentIterations: 0,
logFileName: null,
profileRoot: null,
usePersistentStorage,
fullSolutionAnalysis,
incrementalAnalyzerNames)
{ }
internal Options(
string analyzerPath,
string solutionPath,
ImmutableHashSet<string> analyzerIds,
ImmutableHashSet<string> refactoringNodes,
bool runConcurrent,
bool reportSuppressedDiagnostics,
bool applyChanges,
bool showStats,
bool showCompilerDiagnostics,
bool useAll,
int iterations,
bool testDocuments,
Func<string, bool> testDocumentMatch,
int testDocumentIterations,
string logFileName,
string profileRoot,
bool usePersistentStorage,
bool fullSolutionAnalysis,
ImmutableArray<string> incrementalAnalyzerNames)
{
AnalyzerPath = analyzerPath;
SolutionPath = solutionPath;
AnalyzerNames = analyzerIds;
RefactoringNodes = refactoringNodes;
RunConcurrent = runConcurrent;
ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
ApplyChanges = applyChanges;
ShowStats = showStats;
ShowCompilerDiagnostics = showCompilerDiagnostics;
UseAll = useAll;
Iterations = iterations;
TestDocuments = testDocuments;
TestDocumentMatch = testDocumentMatch;
TestDocumentIterations = testDocumentIterations;
LogFileName = logFileName;
ProfileRoot = profileRoot;
UsePersistentStorage = usePersistentStorage;
FullSolutionAnalysis = fullSolutionAnalysis;
IncrementalAnalyzerNames = incrementalAnalyzerNames;
}
internal static Options Create(string[] args)
{
string analyzerPath = null;
string solutionPath = null;
var builder = ImmutableHashSet.CreateBuilder<string>();
var refactoringBuilder = ImmutableHashSet.CreateBuilder<string>();
bool runConcurrent = false;
bool reportSuppressedDiagnostics = false;
bool applyChanges = false;
bool showStats = false;
bool showCompilerDiagnostics = false;
bool useAll = false;
int iterations = 1;
bool testDocuments = false;
Func<string, bool> testDocumentMatch = _ => true;
int testDocumentIterations = 10;
string logFileName = null;
string profileRoot = null;
var usePersistentStorage = false;
var fullSolutionAnalysis = false;
var incrementalAnalyzerNames = ImmutableArray.CreateBuilder<string>();
int i = 0;
while (i < args.Length)
{
var arg = args[i++];
string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException($"Missing value for option {arg}");
switch (arg)
{
case "/all":
useAll = true;
break;
case "/stats":
showStats = true;
break;
case "/compilerStats":
showCompilerDiagnostics = true;
break;
case "/concurrent":
runConcurrent = true;
break;
case "/editperf":
testDocuments = true;
break;
case var _ when arg.StartsWith("/editperf:"):
testDocuments = true;
var expression = new Regex(arg.Substring("/editperf:".Length), RegexOptions.Compiled | RegexOptions.IgnoreCase);
testDocumentMatch = documentPath => expression.IsMatch(documentPath);
break;
case var _ when arg.StartsWith("/edititer:"):
testDocumentIterations = int.Parse(arg.Substring("/edititer:".Length));
break;
case var _ when arg.StartsWith("/iter:"):
iterations = int.Parse(arg.Substring("/iter:".Length));
break;
case "/suppressed":
reportSuppressedDiagnostics = true;
break;
case "/apply":
applyChanges = true;
break;
case "/a":
builder.Add(ReadValue());
break;
case "/refactor":
refactoringBuilder.Add(ReadValue());
break;
case "/log":
logFileName = ReadValue();
break;
case "/profileroot":
profileRoot = ReadValue();
break;
case "/persist":
usePersistentStorage = true;
break;
case "/fsa":
fullSolutionAnalysis = true;
break;
case "/ia":
incrementalAnalyzerNames.Add(ReadValue());
break;
default:
if (analyzerPath == null)
{
analyzerPath = arg;
}
else if (solutionPath == null)
{
solutionPath = arg;
}
else
{
throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ?
"Unrecognized option " + arg :
"Unrecognized parameter " + arg));
}
break;
}
}
if (analyzerPath == null)
{
throw new InvalidDataException("Missing analyzer path");
}
if (solutionPath == null)
{
throw new InvalidDataException("Missing solution path");
}
return new Options(
analyzerPath: analyzerPath,
solutionPath: solutionPath,
analyzerIds: builder.ToImmutableHashSet(),
refactoringNodes: refactoringBuilder.ToImmutableHashSet(),
runConcurrent: runConcurrent,
reportSuppressedDiagnostics: reportSuppressedDiagnostics,
applyChanges: applyChanges,
showStats: showStats,
showCompilerDiagnostics: showCompilerDiagnostics,
useAll: useAll,
iterations: iterations,
testDocuments: testDocuments,
testDocumentMatch: testDocumentMatch,
testDocumentIterations: testDocumentIterations,
logFileName: logFileName,
profileRoot: profileRoot,
usePersistentStorage: usePersistentStorage,
fullSolutionAnalysis: fullSolutionAnalysis,
incrementalAnalyzerNames: incrementalAnalyzerNames.ToImmutable());
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/VisualBasicTest/Recommendations/ArrayStatements/ReDimKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements
Public Class ReDimKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "ReDim")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements
Public Class ReDimKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "ReDim")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReDimNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "ReDim")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/Core/Portable/CodeFixes/FixAllOccurrences/IFixAllGetFixesService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal interface IFixAllGetFixesService : IWorkspaceService
{
/// <summary>
/// Computes the fix all occurrences code fix, brings up the preview changes dialog for the fix and
/// returns the code action operations corresponding to the fix.
/// </summary>
Task<ImmutableArray<CodeActionOperation>> GetFixAllOperationsAsync(FixAllContext fixAllContext, bool showPreviewChangesDialog);
/// <summary>
/// Computes the fix all occurrences code fix and returns the changed solution.
/// </summary>
Task<Solution> GetFixAllChangedSolutionAsync(FixAllContext fixAllContext);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal interface IFixAllGetFixesService : IWorkspaceService
{
/// <summary>
/// Computes the fix all occurrences code fix, brings up the preview changes dialog for the fix and
/// returns the code action operations corresponding to the fix.
/// </summary>
Task<ImmutableArray<CodeActionOperation>> GetFixAllOperationsAsync(FixAllContext fixAllContext, bool showPreviewChangesDialog);
/// <summary>
/// Computes the fix all occurrences code fix and returns the changed solution.
/// </summary>
Task<Solution> GetFixAllChangedSolutionAsync(FixAllContext fixAllContext);
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/RemoveUnreachableCodeHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
internal static class RemoveUnreachableCodeHelpers
{
public static ImmutableArray<ImmutableArray<StatementSyntax>> GetSubsequentUnreachableSections(StatementSyntax firstUnreachableStatement)
{
SyntaxList<StatementSyntax> siblingStatements;
switch (firstUnreachableStatement.Parent)
{
case BlockSyntax block:
siblingStatements = block.Statements;
break;
case SwitchSectionSyntax switchSection:
siblingStatements = switchSection.Statements;
break;
default:
// We're an embedded statement. So the unreachable section is just us.
return ImmutableArray<ImmutableArray<StatementSyntax>>.Empty;
}
var sections = ArrayBuilder<ImmutableArray<StatementSyntax>>.GetInstance();
var currentSection = ArrayBuilder<StatementSyntax>.GetInstance();
var firstUnreachableStatementIndex = siblingStatements.IndexOf(firstUnreachableStatement);
for (int i = firstUnreachableStatementIndex + 1, n = siblingStatements.Count; i < n; i++)
{
var currentStatement = siblingStatements[i];
if (currentStatement.IsKind(SyntaxKind.LabeledStatement))
{
// In the case of a subsequent labeled statement, we don't want to consider it
// unreachable as there may be a 'goto' somewhere else to that label. If the
// compiler actually thinks that label is unreachable, it will give an diagnostic
// on that label itself and we can use that diagnostic to handle it and any
// subsequent sections.
break;
}
if (currentStatement.IsKind(SyntaxKind.LocalFunctionStatement))
{
// In the case of local functions, it is legal for a local function to be declared
// in code that is otherwise unreachable. It can still be called elsewhere. If
// the local function itself is not called, there will be a particular diagnostic
// for that ("The variable XXX is declared but never used") and the user can choose
// if they want to remove it or not.
var section = currentSection.ToImmutableAndFree();
AddIfNonEmpty(sections, section);
currentSection = ArrayBuilder<StatementSyntax>.GetInstance();
continue;
}
currentSection.Add(currentStatement);
}
var lastSection = currentSection.ToImmutableAndFree();
AddIfNonEmpty(sections, lastSection);
return sections.ToImmutableAndFree();
}
private static void AddIfNonEmpty(ArrayBuilder<ImmutableArray<StatementSyntax>> sections, ImmutableArray<StatementSyntax> lastSection)
{
if (!lastSection.IsEmpty)
{
sections.Add(lastSection);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
internal static class RemoveUnreachableCodeHelpers
{
public static ImmutableArray<ImmutableArray<StatementSyntax>> GetSubsequentUnreachableSections(StatementSyntax firstUnreachableStatement)
{
SyntaxList<StatementSyntax> siblingStatements;
switch (firstUnreachableStatement.Parent)
{
case BlockSyntax block:
siblingStatements = block.Statements;
break;
case SwitchSectionSyntax switchSection:
siblingStatements = switchSection.Statements;
break;
default:
// We're an embedded statement. So the unreachable section is just us.
return ImmutableArray<ImmutableArray<StatementSyntax>>.Empty;
}
var sections = ArrayBuilder<ImmutableArray<StatementSyntax>>.GetInstance();
var currentSection = ArrayBuilder<StatementSyntax>.GetInstance();
var firstUnreachableStatementIndex = siblingStatements.IndexOf(firstUnreachableStatement);
for (int i = firstUnreachableStatementIndex + 1, n = siblingStatements.Count; i < n; i++)
{
var currentStatement = siblingStatements[i];
if (currentStatement.IsKind(SyntaxKind.LabeledStatement))
{
// In the case of a subsequent labeled statement, we don't want to consider it
// unreachable as there may be a 'goto' somewhere else to that label. If the
// compiler actually thinks that label is unreachable, it will give an diagnostic
// on that label itself and we can use that diagnostic to handle it and any
// subsequent sections.
break;
}
if (currentStatement.IsKind(SyntaxKind.LocalFunctionStatement))
{
// In the case of local functions, it is legal for a local function to be declared
// in code that is otherwise unreachable. It can still be called elsewhere. If
// the local function itself is not called, there will be a particular diagnostic
// for that ("The variable XXX is declared but never used") and the user can choose
// if they want to remove it or not.
var section = currentSection.ToImmutableAndFree();
AddIfNonEmpty(sections, section);
currentSection = ArrayBuilder<StatementSyntax>.GetInstance();
continue;
}
currentSection.Add(currentStatement);
}
var lastSection = currentSection.ToImmutableAndFree();
AddIfNonEmpty(sections, lastSection);
return sections.ToImmutableAndFree();
}
private static void AddIfNonEmpty(ArrayBuilder<ImmutableArray<StatementSyntax>> sections, ImmutableArray<StatementSyntax> lastSection)
{
if (!lastSection.IsEmpty)
{
sections.Add(lastSection);
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/CSharp/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.Comparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class MemberDeclarationsOrganizer
{
private class Comparer : IComparer<MemberDeclarationSyntax>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum OuterOrdering
{
Fields,
EventFields,
Constructors,
Destructors,
Properties,
Events,
Indexers,
Operators,
ConversionOperators,
Methods,
Types,
Remaining
}
private enum InnerOrdering
{
StaticInstance,
Accessibility,
Name
}
private enum Accessibility
{
Public,
Protected,
ProtectedOrInternal,
Internal,
Private
}
public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y)
{
if (x == y)
{
return 0;
}
var xOuterOrdering = GetOuterOrdering(x);
var yOuterOrdering = GetOuterOrdering(y);
var compare = xOuterOrdering - yOuterOrdering;
if (compare != 0)
{
return compare;
}
if (xOuterOrdering == OuterOrdering.Remaining)
{
return 1;
}
else if (yOuterOrdering == OuterOrdering.Remaining)
{
return -1;
}
if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields)
{
// Fields with initializers can't be reordered relative to
// themselves due to ordering issues.
var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null);
var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null);
if (xHasInitializer && yHasInitializer)
{
return 0;
}
}
var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0)
{
return compare;
}
var xAccessibility = GetAccessibility(x);
var yAccessibility = GetAccessibility(y);
if ((compare = xAccessibility - yAccessibility) != 0)
{
return compare;
}
var xName = ShouldCompareByName(x) ? x.GetNameToken() : default;
var yName = ShouldCompareByName(y) ? y.GetNameToken() : default;
if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0)
{
return compare;
}
// Their names were the same. Order them by arity at this point.
return x.GetArity() - y.GetArity();
}
private static Accessibility GetAccessibility(MemberDeclarationSyntax x)
{
var xModifiers = x.GetModifiers();
if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return Accessibility.Public;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.ProtectedOrInternal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.Internal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return Accessibility.Protected;
}
else
{
return Accessibility.Private;
}
}
private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x)
{
switch (x.Kind())
{
case SyntaxKind.FieldDeclaration:
return OuterOrdering.Fields;
case SyntaxKind.EventFieldDeclaration:
return OuterOrdering.EventFields;
case SyntaxKind.ConstructorDeclaration:
return OuterOrdering.Constructors;
case SyntaxKind.DestructorDeclaration:
return OuterOrdering.Destructors;
case SyntaxKind.PropertyDeclaration:
return OuterOrdering.Properties;
case SyntaxKind.EventDeclaration:
return OuterOrdering.Events;
case SyntaxKind.IndexerDeclaration:
return OuterOrdering.Indexers;
case SyntaxKind.OperatorDeclaration:
return OuterOrdering.Operators;
case SyntaxKind.ConversionOperatorDeclaration:
return OuterOrdering.ConversionOperators;
case SyntaxKind.MethodDeclaration:
return OuterOrdering.Methods;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return OuterOrdering.Types;
default:
return OuterOrdering.Remaining;
}
}
private static bool ShouldCompareByName(MemberDeclarationSyntax x)
{
// Constructors, destructors, indexers and operators should not be sorted by name.
// Note: Conversion operators should not be sorted by name either, but it's not
// necessary to deal with that here, because GetNameToken cannot return a
// name for them (there's only a NameSyntax, not a Token).
switch (x.Kind())
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
return false;
default:
return true;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class MemberDeclarationsOrganizer
{
private class Comparer : IComparer<MemberDeclarationSyntax>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum OuterOrdering
{
Fields,
EventFields,
Constructors,
Destructors,
Properties,
Events,
Indexers,
Operators,
ConversionOperators,
Methods,
Types,
Remaining
}
private enum InnerOrdering
{
StaticInstance,
Accessibility,
Name
}
private enum Accessibility
{
Public,
Protected,
ProtectedOrInternal,
Internal,
Private
}
public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y)
{
if (x == y)
{
return 0;
}
var xOuterOrdering = GetOuterOrdering(x);
var yOuterOrdering = GetOuterOrdering(y);
var compare = xOuterOrdering - yOuterOrdering;
if (compare != 0)
{
return compare;
}
if (xOuterOrdering == OuterOrdering.Remaining)
{
return 1;
}
else if (yOuterOrdering == OuterOrdering.Remaining)
{
return -1;
}
if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields)
{
// Fields with initializers can't be reordered relative to
// themselves due to ordering issues.
var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null);
var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null);
if (xHasInitializer && yHasInitializer)
{
return 0;
}
}
var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword);
if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0)
{
return compare;
}
var xAccessibility = GetAccessibility(x);
var yAccessibility = GetAccessibility(y);
if ((compare = xAccessibility - yAccessibility) != 0)
{
return compare;
}
var xName = ShouldCompareByName(x) ? x.GetNameToken() : default;
var yName = ShouldCompareByName(y) ? y.GetNameToken() : default;
if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0)
{
return compare;
}
// Their names were the same. Order them by arity at this point.
return x.GetArity() - y.GetArity();
}
private static Accessibility GetAccessibility(MemberDeclarationSyntax x)
{
var xModifiers = x.GetModifiers();
if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return Accessibility.Public;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.ProtectedOrInternal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return Accessibility.Internal;
}
else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return Accessibility.Protected;
}
else
{
return Accessibility.Private;
}
}
private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x)
{
switch (x.Kind())
{
case SyntaxKind.FieldDeclaration:
return OuterOrdering.Fields;
case SyntaxKind.EventFieldDeclaration:
return OuterOrdering.EventFields;
case SyntaxKind.ConstructorDeclaration:
return OuterOrdering.Constructors;
case SyntaxKind.DestructorDeclaration:
return OuterOrdering.Destructors;
case SyntaxKind.PropertyDeclaration:
return OuterOrdering.Properties;
case SyntaxKind.EventDeclaration:
return OuterOrdering.Events;
case SyntaxKind.IndexerDeclaration:
return OuterOrdering.Indexers;
case SyntaxKind.OperatorDeclaration:
return OuterOrdering.Operators;
case SyntaxKind.ConversionOperatorDeclaration:
return OuterOrdering.ConversionOperators;
case SyntaxKind.MethodDeclaration:
return OuterOrdering.Methods;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return OuterOrdering.Types;
default:
return OuterOrdering.Remaining;
}
}
private static bool ShouldCompareByName(MemberDeclarationSyntax x)
{
// Constructors, destructors, indexers and operators should not be sorted by name.
// Note: Conversion operators should not be sorted by name either, but it's not
// necessary to deal with that here, because GetNameToken cannot return a
// name for them (there's only a NameSyntax, not a Token).
switch (x.Kind())
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
return false;
default:
return true;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/EditorFeatures/Core.Cocoa/CommandHandlers/GoToMatchingBraceCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(GoToMatchingBraceCommandHandler))]
internal class GoToMatchingBraceCommandHandler : VSCommanding.ICommandHandler<GotoBraceCommandArgs>
{
private readonly IBraceMatchingService _braceMatchingService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToMatchingBraceCommandHandler(IBraceMatchingService braceMatchingService)
{
_braceMatchingService = braceMatchingService ??
throw new ArgumentNullException(nameof(braceMatchingService));
}
public string DisplayName => nameof(GoToMatchingBraceCommandHandler);
public bool ExecuteCommand(GotoBraceCommandArgs args, VSCommanding.CommandExecutionContext executionContext)
{
var snapshot = args.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
var caretPosition = args.TextView.Caret.Position.BufferPosition.Position;
var task = _braceMatchingService.FindMatchingSpanAsync(document, caretPosition, executionContext.OperationContext.UserCancellationToken);
var span = task.WaitAndGetResult(executionContext.OperationContext.UserCancellationToken);
if (!span.HasValue)
return false;
if (span.Value.Start < caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.Start));
else if (span.Value.End > caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.End));
return true;
}
public VSCommanding.CommandState GetCommandState(GotoBraceCommandArgs args)
{
return VSCommanding.CommandState.Available;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(GoToMatchingBraceCommandHandler))]
internal class GoToMatchingBraceCommandHandler : VSCommanding.ICommandHandler<GotoBraceCommandArgs>
{
private readonly IBraceMatchingService _braceMatchingService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToMatchingBraceCommandHandler(IBraceMatchingService braceMatchingService)
{
_braceMatchingService = braceMatchingService ??
throw new ArgumentNullException(nameof(braceMatchingService));
}
public string DisplayName => nameof(GoToMatchingBraceCommandHandler);
public bool ExecuteCommand(GotoBraceCommandArgs args, VSCommanding.CommandExecutionContext executionContext)
{
var snapshot = args.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
var caretPosition = args.TextView.Caret.Position.BufferPosition.Position;
var task = _braceMatchingService.FindMatchingSpanAsync(document, caretPosition, executionContext.OperationContext.UserCancellationToken);
var span = task.WaitAndGetResult(executionContext.OperationContext.UserCancellationToken);
if (!span.HasValue)
return false;
if (span.Value.Start < caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.Start));
else if (span.Value.End > caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.End));
return true;
}
public VSCommanding.CommandState GetCommandState(GotoBraceCommandArgs args)
{
return VSCommanding.CommandState.Available;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Portable/Declarations/MergedNamespaceDeclaration.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.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
' An invariant of a merged declaration is that all of its children
' are also merged declarations.
Friend NotInheritable Class MergedNamespaceDeclaration
Inherits MergedNamespaceOrTypeDeclaration
Private ReadOnly _declarations As ImmutableArray(Of SingleNamespaceDeclaration)
Private ReadOnly _multipleSpellings As Boolean ' true if the namespace is spelling with multiple different case-insensitive spellings ("Namespace GOO" and "Namespace goo")
Private _children As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Private Sub New(declarations As ImmutableArray(Of SingleNamespaceDeclaration))
MyBase.New(String.Empty)
If declarations.Any() Then
Me.Name = SingleNamespaceDeclaration.BestName(Of SingleNamespaceDeclaration)(declarations, _multipleSpellings)
End If
Me._declarations = declarations
End Sub
Public Shared Function Create(declarations As IEnumerable(Of SingleNamespaceDeclaration)) As MergedNamespaceDeclaration
Return New MergedNamespaceDeclaration(ImmutableArray.CreateRange(Of SingleNamespaceDeclaration)(declarations))
End Function
Public Shared Function Create(ParamArray declarations As SingleNamespaceDeclaration()) As MergedNamespaceDeclaration
Return New MergedNamespaceDeclaration(declarations.AsImmutableOrNull)
End Function
Public Overrides ReadOnly Property Kind As DeclarationKind
Get
Return DeclarationKind.Namespace
End Get
End Property
Public ReadOnly Property Declarations As ImmutableArray(Of SingleNamespaceDeclaration)
Get
Return _declarations
End Get
End Property
Public Function GetLexicalSortKey(compilation As VisualBasicCompilation) As LexicalSortKey
' Return first sort key from all declarations.
Dim sortKey As LexicalSortKey = New LexicalSortKey(_declarations(0).NameLocation, compilation)
For i = 1 To _declarations.Length - 1
sortKey = LexicalSortKey.First(sortKey, New LexicalSortKey(_declarations(i).NameLocation, compilation))
Next
Return sortKey
End Function
Public ReadOnly Property NameLocations As ImmutableArray(Of Location)
Get
If _declarations.Length = 1 Then
Dim loc = _declarations(0).NameLocation
If loc Is Nothing Then
Return ImmutableArray(Of Location).Empty
End If
Return ImmutableArray.Create(loc)
End If
Dim builder = ArrayBuilder(Of Location).GetInstance()
For Each decl In _declarations
Dim loc = decl.NameLocation
If loc IsNot Nothing Then
builder.Add(loc)
End If
Next
Return builder.ToImmutableAndFree()
End Get
End Property
Public ReadOnly Property SyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Dim references = ArrayBuilder(Of SyntaxReference).GetInstance()
For Each decl In _declarations
If decl.SyntaxReference IsNot Nothing Then
references.Add(decl.SyntaxReference)
End If
Next
Return references.ToImmutableAndFree()
End Get
End Property
Protected Overrides Function GetDeclarationChildren() As ImmutableArray(Of Declaration)
Return StaticCast(Of Declaration).From(Me.Children)
End Function
Private Function MakeChildren() As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Dim childNamespaces = ArrayBuilder(Of SingleNamespaceDeclaration).GetInstance()
Dim singleTypeDeclarations = ArrayBuilder(Of SingleTypeDeclaration).GetInstance()
' Distribute declarations into the two lists
For Each d As SingleNamespaceDeclaration In _declarations
For Each child As SingleNamespaceOrTypeDeclaration In d.Children
Dim singleNamespaceDeclaration As SingleNamespaceDeclaration = TryCast(child, SingleNamespaceDeclaration)
If singleNamespaceDeclaration IsNot Nothing Then
childNamespaces.Add(singleNamespaceDeclaration)
Else
singleTypeDeclarations.Add(DirectCast(child, SingleTypeDeclaration))
End If
Next
Next
Dim result As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration) = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance()
' Merge and add the namespaces
Select Case childNamespaces.Count
Case 0
' Do nothing
Case 1
' Add a single element
result.Add(MergedNamespaceDeclaration.Create(childNamespaces))
Case 2
' Could be one group or two
If SingleNamespaceDeclaration.EqualityComparer.Equals(childNamespaces(0), childNamespaces(1)) Then
result.Add(MergedNamespaceDeclaration.Create(childNamespaces))
Else
result.Add(MergedNamespaceDeclaration.Create(childNamespaces(0)))
result.Add(MergedNamespaceDeclaration.Create(childNamespaces(1)))
End If
Case Else
' Three or more. Use GroupBy to add by groups.
For Each group In childNamespaces.GroupBy(Function(n) n, SingleNamespaceDeclaration.EqualityComparer)
result.Add(MergedNamespaceDeclaration.Create(group))
Next
End Select
childNamespaces.Free()
' Merge and add the types
If singleTypeDeclarations.Count <> 0 Then
result.AddRange(MergedTypeDeclaration.MakeMergedTypes(singleTypeDeclarations))
End If
singleTypeDeclarations.Free()
Return result.ToImmutableAndFree()
End Function
Public Overloads ReadOnly Property Children As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Get
If Me._children.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(Me._children, MakeChildren())
End If
Return Me._children
End Get
End Property
' Is this declaration merged from declarations with different case-sensitive spellings
' (i.e., "Namespace GOO" and "Namespace goo".
Public ReadOnly Property HasMultipleSpellings As Boolean
Get
Return _multipleSpellings
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
' An invariant of a merged declaration is that all of its children
' are also merged declarations.
Friend NotInheritable Class MergedNamespaceDeclaration
Inherits MergedNamespaceOrTypeDeclaration
Private ReadOnly _declarations As ImmutableArray(Of SingleNamespaceDeclaration)
Private ReadOnly _multipleSpellings As Boolean ' true if the namespace is spelling with multiple different case-insensitive spellings ("Namespace GOO" and "Namespace goo")
Private _children As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Private Sub New(declarations As ImmutableArray(Of SingleNamespaceDeclaration))
MyBase.New(String.Empty)
If declarations.Any() Then
Me.Name = SingleNamespaceDeclaration.BestName(Of SingleNamespaceDeclaration)(declarations, _multipleSpellings)
End If
Me._declarations = declarations
End Sub
Public Shared Function Create(declarations As IEnumerable(Of SingleNamespaceDeclaration)) As MergedNamespaceDeclaration
Return New MergedNamespaceDeclaration(ImmutableArray.CreateRange(Of SingleNamespaceDeclaration)(declarations))
End Function
Public Shared Function Create(ParamArray declarations As SingleNamespaceDeclaration()) As MergedNamespaceDeclaration
Return New MergedNamespaceDeclaration(declarations.AsImmutableOrNull)
End Function
Public Overrides ReadOnly Property Kind As DeclarationKind
Get
Return DeclarationKind.Namespace
End Get
End Property
Public ReadOnly Property Declarations As ImmutableArray(Of SingleNamespaceDeclaration)
Get
Return _declarations
End Get
End Property
Public Function GetLexicalSortKey(compilation As VisualBasicCompilation) As LexicalSortKey
' Return first sort key from all declarations.
Dim sortKey As LexicalSortKey = New LexicalSortKey(_declarations(0).NameLocation, compilation)
For i = 1 To _declarations.Length - 1
sortKey = LexicalSortKey.First(sortKey, New LexicalSortKey(_declarations(i).NameLocation, compilation))
Next
Return sortKey
End Function
Public ReadOnly Property NameLocations As ImmutableArray(Of Location)
Get
If _declarations.Length = 1 Then
Dim loc = _declarations(0).NameLocation
If loc Is Nothing Then
Return ImmutableArray(Of Location).Empty
End If
Return ImmutableArray.Create(loc)
End If
Dim builder = ArrayBuilder(Of Location).GetInstance()
For Each decl In _declarations
Dim loc = decl.NameLocation
If loc IsNot Nothing Then
builder.Add(loc)
End If
Next
Return builder.ToImmutableAndFree()
End Get
End Property
Public ReadOnly Property SyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Dim references = ArrayBuilder(Of SyntaxReference).GetInstance()
For Each decl In _declarations
If decl.SyntaxReference IsNot Nothing Then
references.Add(decl.SyntaxReference)
End If
Next
Return references.ToImmutableAndFree()
End Get
End Property
Protected Overrides Function GetDeclarationChildren() As ImmutableArray(Of Declaration)
Return StaticCast(Of Declaration).From(Me.Children)
End Function
Private Function MakeChildren() As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Dim childNamespaces = ArrayBuilder(Of SingleNamespaceDeclaration).GetInstance()
Dim singleTypeDeclarations = ArrayBuilder(Of SingleTypeDeclaration).GetInstance()
' Distribute declarations into the two lists
For Each d As SingleNamespaceDeclaration In _declarations
For Each child As SingleNamespaceOrTypeDeclaration In d.Children
Dim singleNamespaceDeclaration As SingleNamespaceDeclaration = TryCast(child, SingleNamespaceDeclaration)
If singleNamespaceDeclaration IsNot Nothing Then
childNamespaces.Add(singleNamespaceDeclaration)
Else
singleTypeDeclarations.Add(DirectCast(child, SingleTypeDeclaration))
End If
Next
Next
Dim result As ArrayBuilder(Of MergedNamespaceOrTypeDeclaration) = ArrayBuilder(Of MergedNamespaceOrTypeDeclaration).GetInstance()
' Merge and add the namespaces
Select Case childNamespaces.Count
Case 0
' Do nothing
Case 1
' Add a single element
result.Add(MergedNamespaceDeclaration.Create(childNamespaces))
Case 2
' Could be one group or two
If SingleNamespaceDeclaration.EqualityComparer.Equals(childNamespaces(0), childNamespaces(1)) Then
result.Add(MergedNamespaceDeclaration.Create(childNamespaces))
Else
result.Add(MergedNamespaceDeclaration.Create(childNamespaces(0)))
result.Add(MergedNamespaceDeclaration.Create(childNamespaces(1)))
End If
Case Else
' Three or more. Use GroupBy to add by groups.
For Each group In childNamespaces.GroupBy(Function(n) n, SingleNamespaceDeclaration.EqualityComparer)
result.Add(MergedNamespaceDeclaration.Create(group))
Next
End Select
childNamespaces.Free()
' Merge and add the types
If singleTypeDeclarations.Count <> 0 Then
result.AddRange(MergedTypeDeclaration.MakeMergedTypes(singleTypeDeclarations))
End If
singleTypeDeclarations.Free()
Return result.ToImmutableAndFree()
End Function
Public Overloads ReadOnly Property Children As ImmutableArray(Of MergedNamespaceOrTypeDeclaration)
Get
If Me._children.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(Me._children, MakeChildren())
End If
Return Me._children
End Get
End Property
' Is this declaration merged from declarations with different case-sensitive spellings
' (i.e., "Namespace GOO" and "Namespace goo".
Public ReadOnly Property HasMultipleSpellings As Boolean
Get
Return _multipleSpellings
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIncrementOrDecrementOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IIncrementOrDecrementOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void IncrementOrDecrementFlow_01()
{
string source = @"
class C
{
void M(int i, int j)
/*<bind>*/{
j = --i;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = --i;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = --i')
Left:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Right:
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i')
Target:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void IncrementOrDecrementFlow_02()
{
string source = @"
class C
{
void M(D x, D y)
/*<bind>*/{
(x ?? y).i++;
}/*</bind>*/
public class D { public int i; }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.D) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.D) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(x ?? y).i++;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: '(x ?? y).i++')
Target:
IFieldReferenceOperation: System.Int32 C.D.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ?? y).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x ?? y')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IIncrementOrDecrementOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void IncrementOrDecrementFlow_01()
{
string source = @"
class C
{
void M(int i, int j)
/*<bind>*/{
j = --i;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = --i;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = --i')
Left:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Right:
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i')
Target:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void IncrementOrDecrementFlow_02()
{
string source = @"
class C
{
void M(D x, D y)
/*<bind>*/{
(x ?? y).i++;
}/*</bind>*/
public class D { public int i; }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.D) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.D) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(x ?? y).i++;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: '(x ?? y).i++')
Target:
IFieldReferenceOperation: System.Int32 C.D.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ?? y).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.D, IsImplicit) (Syntax: 'x ?? y')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Tools/ExternalAccess/Razor/RazorPredefinedCodeRefactoringProviderNames.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeRefactorings;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal static class RazorPredefinedCodeRefactoringProviderNames
{
public static string AddAwait => PredefinedCodeRefactoringProviderNames.AddAwait;
public static string AddConstructorParametersFromMembers => PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers;
public static string AddFileBanner => PredefinedCodeRefactoringProviderNames.AddFileBanner;
public static string AddMissingImports => PredefinedCodeRefactoringProviderNames.AddMissingImports;
public static string ChangeSignature => PredefinedCodeRefactoringProviderNames.ChangeSignature;
public static string ConvertAnonymousTypeToClass => PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass;
public static string ConvertDirectCastToTryCast => PredefinedCodeRefactoringProviderNames.ConvertDirectCastToTryCast;
public static string ConvertTryCastToDirectCast => PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast;
public static string ConvertToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString;
public static string ConvertTupleToStruct => PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct;
public static string EncapsulateField => PredefinedCodeRefactoringProviderNames.EncapsulateField;
public static string ExtractClass => PredefinedCodeRefactoringProviderNames.ExtractClass;
public static string ExtractInterface => PredefinedCodeRefactoringProviderNames.ExtractInterface;
public static string ExtractMethod => PredefinedCodeRefactoringProviderNames.ExtractMethod;
public static string GenerateConstructorFromMembers => PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers;
public static string GenerateDefaultConstructors => PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors;
public static string GenerateEqualsAndGetHashCodeFromMembers => PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers;
public static string GenerateOverrides => PredefinedCodeRefactoringProviderNames.GenerateOverrides;
public static string InlineTemporary => PredefinedCodeRefactoringProviderNames.InlineTemporary;
public static string IntroduceUsingStatement => PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement;
public static string IntroduceVariable => PredefinedCodeRefactoringProviderNames.IntroduceVariable;
public static string InvertConditional => PredefinedCodeRefactoringProviderNames.InvertConditional;
public static string InvertIf => PredefinedCodeRefactoringProviderNames.InvertIf;
public static string InvertLogical => PredefinedCodeRefactoringProviderNames.InvertLogical;
public static string MergeConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.MergeConsecutiveIfStatements;
public static string MergeNestedIfStatements => PredefinedCodeRefactoringProviderNames.MergeNestedIfStatements;
public static string MoveDeclarationNearReference => PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference;
public static string MoveToNamespace => PredefinedCodeRefactoringProviderNames.MoveToNamespace;
public static string MoveTypeToFile => PredefinedCodeRefactoringProviderNames.MoveTypeToFile;
public static string PullMemberUp => PredefinedCodeRefactoringProviderNames.PullMemberUp;
public static string InlineMethod => PredefinedCodeRefactoringProviderNames.InlineMethod;
public static string ReplaceDocCommentTextWithTag => PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag;
public static string SplitIntoConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements;
public static string SplitIntoNestedIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoNestedIfStatements;
public static string SyncNamespace => PredefinedCodeRefactoringProviderNames.SyncNamespace;
public static string UseExplicitType => PredefinedCodeRefactoringProviderNames.UseExplicitType;
public static string UseExpressionBody => PredefinedCodeRefactoringProviderNames.UseExpressionBody;
public static string UseImplicitType => PredefinedCodeRefactoringProviderNames.UseImplicitType;
public static string Wrapping => PredefinedCodeRefactoringProviderNames.Wrapping;
public static string MakeLocalFunctionStatic => PredefinedCodeRefactoringProviderNames.MakeLocalFunctionStatic;
public static string GenerateComparisonOperators => PredefinedCodeRefactoringProviderNames.GenerateComparisonOperators;
public static string ReplacePropertyWithMethods => PredefinedCodeRefactoringProviderNames.ReplacePropertyWithMethods;
public static string ReplaceMethodWithProperty => PredefinedCodeRefactoringProviderNames.ReplaceMethodWithProperty;
public static string AddDebuggerDisplay => PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay;
public static string ConvertAutoPropertyToFullProperty => PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty;
public static string ReverseForStatement => PredefinedCodeRefactoringProviderNames.ReverseForStatement;
public static string ConvertLocalFunctionToMethod => PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod;
public static string ConvertForEachToFor => PredefinedCodeRefactoringProviderNames.ConvertForEachToFor;
public static string ConvertLinqQueryToForEach => PredefinedCodeRefactoringProviderNames.ConvertLinqQueryToForEach;
public static string ConvertForEachToLinqQuery => PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery;
public static string ConvertNumericLiteral => PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral;
public static string IntroduceLocalForExpression => PredefinedCodeRefactoringProviderNames.IntroduceLocalForExpression;
public static string AddParameterCheck => PredefinedCodeRefactoringProviderNames.AddParameterCheck;
public static string InitializeMemberFromParameter => PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter;
public static string NameTupleElement => PredefinedCodeRefactoringProviderNames.NameTupleElement;
public static string UseNamedArguments => PredefinedCodeRefactoringProviderNames.UseNamedArguments;
public static string ConvertForToForEach => PredefinedCodeRefactoringProviderNames.ConvertForToForEach;
public static string ConvertIfToSwitch => PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch;
public static string ConvertBetweenRegularAndVerbatimString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString;
public static string ConvertBetweenRegularAndVerbatimInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString;
public static string RenameTracking => PredefinedCodeRefactoringProviderNames.RenameTracking;
public static string UseExpressionBodyForLambda => PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda;
public static string ImplementInterfaceExplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly;
public static string ImplementInterfaceImplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceImplicitly;
public static string ConvertPlaceholderToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString;
public static string ConvertConcatenationToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertConcatenationToInterpolatedString;
public static string InvertMultiLineIf => PredefinedCodeRefactoringProviderNames.InvertMultiLineIf;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeRefactorings;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal static class RazorPredefinedCodeRefactoringProviderNames
{
public static string AddAwait => PredefinedCodeRefactoringProviderNames.AddAwait;
public static string AddConstructorParametersFromMembers => PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers;
public static string AddFileBanner => PredefinedCodeRefactoringProviderNames.AddFileBanner;
public static string AddMissingImports => PredefinedCodeRefactoringProviderNames.AddMissingImports;
public static string ChangeSignature => PredefinedCodeRefactoringProviderNames.ChangeSignature;
public static string ConvertAnonymousTypeToClass => PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass;
public static string ConvertDirectCastToTryCast => PredefinedCodeRefactoringProviderNames.ConvertDirectCastToTryCast;
public static string ConvertTryCastToDirectCast => PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast;
public static string ConvertToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString;
public static string ConvertTupleToStruct => PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct;
public static string EncapsulateField => PredefinedCodeRefactoringProviderNames.EncapsulateField;
public static string ExtractClass => PredefinedCodeRefactoringProviderNames.ExtractClass;
public static string ExtractInterface => PredefinedCodeRefactoringProviderNames.ExtractInterface;
public static string ExtractMethod => PredefinedCodeRefactoringProviderNames.ExtractMethod;
public static string GenerateConstructorFromMembers => PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers;
public static string GenerateDefaultConstructors => PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors;
public static string GenerateEqualsAndGetHashCodeFromMembers => PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers;
public static string GenerateOverrides => PredefinedCodeRefactoringProviderNames.GenerateOverrides;
public static string InlineTemporary => PredefinedCodeRefactoringProviderNames.InlineTemporary;
public static string IntroduceUsingStatement => PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement;
public static string IntroduceVariable => PredefinedCodeRefactoringProviderNames.IntroduceVariable;
public static string InvertConditional => PredefinedCodeRefactoringProviderNames.InvertConditional;
public static string InvertIf => PredefinedCodeRefactoringProviderNames.InvertIf;
public static string InvertLogical => PredefinedCodeRefactoringProviderNames.InvertLogical;
public static string MergeConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.MergeConsecutiveIfStatements;
public static string MergeNestedIfStatements => PredefinedCodeRefactoringProviderNames.MergeNestedIfStatements;
public static string MoveDeclarationNearReference => PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference;
public static string MoveToNamespace => PredefinedCodeRefactoringProviderNames.MoveToNamespace;
public static string MoveTypeToFile => PredefinedCodeRefactoringProviderNames.MoveTypeToFile;
public static string PullMemberUp => PredefinedCodeRefactoringProviderNames.PullMemberUp;
public static string InlineMethod => PredefinedCodeRefactoringProviderNames.InlineMethod;
public static string ReplaceDocCommentTextWithTag => PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag;
public static string SplitIntoConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements;
public static string SplitIntoNestedIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoNestedIfStatements;
public static string SyncNamespace => PredefinedCodeRefactoringProviderNames.SyncNamespace;
public static string UseExplicitType => PredefinedCodeRefactoringProviderNames.UseExplicitType;
public static string UseExpressionBody => PredefinedCodeRefactoringProviderNames.UseExpressionBody;
public static string UseImplicitType => PredefinedCodeRefactoringProviderNames.UseImplicitType;
public static string Wrapping => PredefinedCodeRefactoringProviderNames.Wrapping;
public static string MakeLocalFunctionStatic => PredefinedCodeRefactoringProviderNames.MakeLocalFunctionStatic;
public static string GenerateComparisonOperators => PredefinedCodeRefactoringProviderNames.GenerateComparisonOperators;
public static string ReplacePropertyWithMethods => PredefinedCodeRefactoringProviderNames.ReplacePropertyWithMethods;
public static string ReplaceMethodWithProperty => PredefinedCodeRefactoringProviderNames.ReplaceMethodWithProperty;
public static string AddDebuggerDisplay => PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay;
public static string ConvertAutoPropertyToFullProperty => PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty;
public static string ReverseForStatement => PredefinedCodeRefactoringProviderNames.ReverseForStatement;
public static string ConvertLocalFunctionToMethod => PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod;
public static string ConvertForEachToFor => PredefinedCodeRefactoringProviderNames.ConvertForEachToFor;
public static string ConvertLinqQueryToForEach => PredefinedCodeRefactoringProviderNames.ConvertLinqQueryToForEach;
public static string ConvertForEachToLinqQuery => PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery;
public static string ConvertNumericLiteral => PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral;
public static string IntroduceLocalForExpression => PredefinedCodeRefactoringProviderNames.IntroduceLocalForExpression;
public static string AddParameterCheck => PredefinedCodeRefactoringProviderNames.AddParameterCheck;
public static string InitializeMemberFromParameter => PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter;
public static string NameTupleElement => PredefinedCodeRefactoringProviderNames.NameTupleElement;
public static string UseNamedArguments => PredefinedCodeRefactoringProviderNames.UseNamedArguments;
public static string ConvertForToForEach => PredefinedCodeRefactoringProviderNames.ConvertForToForEach;
public static string ConvertIfToSwitch => PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch;
public static string ConvertBetweenRegularAndVerbatimString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString;
public static string ConvertBetweenRegularAndVerbatimInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString;
public static string RenameTracking => PredefinedCodeRefactoringProviderNames.RenameTracking;
public static string UseExpressionBodyForLambda => PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda;
public static string ImplementInterfaceExplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly;
public static string ImplementInterfaceImplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceImplicitly;
public static string ConvertPlaceholderToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString;
public static string ConvertConcatenationToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertConcatenationToInterpolatedString;
public static string InvertMultiLineIf => PredefinedCodeRefactoringProviderNames.InvertMultiLineIf;
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/Core/Impl/CodeModel/TextManagerAdapter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal sealed class TextManagerAdapter : ITextManagerAdapter
{
public EnvDTE.TextPoint CreateTextPoint(FileCodeModel fileCodeModel, VirtualTreePoint point)
{
if (!fileCodeModel.TryGetDocument(out var document))
{
return null;
}
var hierarchyOpt = fileCodeModel.Workspace.GetHierarchy(document.Project.Id);
using var invisibleEditor = new InvisibleEditor(fileCodeModel.ServiceProvider, document.FilePath, hierarchyOpt, needsSave: false, needsUndoDisabled: false);
var vsTextLines = invisibleEditor.VsTextLines;
var line = point.GetContainingLine();
var column = point.Position - line.Start + point.VirtualSpaces;
Marshal.ThrowExceptionForHR(vsTextLines.CreateTextPoint(line.LineNumber, column, out var textPoint));
return (EnvDTE.TextPoint)textPoint;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal sealed class TextManagerAdapter : ITextManagerAdapter
{
public EnvDTE.TextPoint CreateTextPoint(FileCodeModel fileCodeModel, VirtualTreePoint point)
{
if (!fileCodeModel.TryGetDocument(out var document))
{
return null;
}
var hierarchyOpt = fileCodeModel.Workspace.GetHierarchy(document.Project.Id);
using var invisibleEditor = new InvisibleEditor(fileCodeModel.ServiceProvider, document.FilePath, hierarchyOpt, needsSave: false, needsUndoDisabled: false);
var vsTextLines = invisibleEditor.VsTextLines;
var line = point.GetContainingLine();
var column = point.Position - line.Start + point.VirtualSpaces;
Marshal.ThrowExceptionForHR(vsTextLines.CreateTextPoint(line.LineNumber, column, out var textPoint));
return (EnvDTE.TextPoint)textPoint;
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualChar.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars
{
/// <summary>
/// <see cref="VirtualChar"/> provides a uniform view of a language's string token characters regardless if they
/// were written raw in source, or are the production of a language escape sequence. For example, in C#, in a
/// normal <c>""</c> string a <c>Tab</c> character can be written either as the raw tab character (value <c>9</c> in
/// ASCII), or as <c>\t</c>. The format is a single character in the source, while the latter is two characters
/// (<c>\</c> and <c>t</c>). <see cref="VirtualChar"/> will represent both, providing the raw <see cref="char"/>
/// value of <c>9</c> as well as what <see cref="TextSpan"/> in the original <see cref="SourceText"/> they occupied.
/// </summary>
/// <remarks>
/// A core consumer of this system is the Regex parser. That parser wants to work over an array of characters,
/// however this array of characters is not the same as the array of characters a user types into a string in C# or
/// VB. For example In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z"
/// and the same as "\\\u007a". However, as these all have wildly different presentations for the user, there needs
/// to be a way to map back the characters it sees ( '\' and 'z' ) back to the ranges of characters the user wrote.
/// </remarks>
internal readonly struct VirtualChar : IEquatable<VirtualChar>, IComparable<VirtualChar>, IComparable<char>
{
/// <summary>
/// The value of this <see cref="VirtualChar"/> as a <see cref="Rune"/> if such a represention is possible.
/// <see cref="Rune"/>s can represent Unicode codepoints that can appear in a <see cref="string"/> except for
/// unpaired surrogates. If an unpaired high or low surrogate character is present, this value will be <see
/// cref="Rune.ReplacementChar"/>. The value of this character can be retrieved from
/// <see cref="SurrogateChar"/>.
/// </summary>
public readonly Rune Rune;
/// <summary>
/// The unpaired high or low surrogate character that was encountered that could not be represented in <see
/// cref="Rune"/>. If <see cref="Rune"/> is not <see cref="Rune.ReplacementChar"/>, this will be <c>0</c>.
/// </summary>
public readonly char SurrogateChar;
/// <summary>
/// The span of characters in the original <see cref="SourceText"/> that represent this <see
/// cref="VirtualChar"/>.
/// </summary>
public readonly TextSpan Span;
/// <summary>
/// Creates a new <see cref="VirtualChar"/> from the provided <paramref name="rune"/>. This operation cannot
/// fail.
/// </summary>
public static VirtualChar Create(Rune rune, TextSpan span)
=> new(rune, surrogateChar: default, span);
/// <summary>
/// Creates a new <see cref="VirtualChar"/> from an unpaired high or low surrogate character. This will throw
/// if <paramref name="surrogateChar"/> is not actually a surrogate character. The resultant <see cref="Rune"/>
/// value will be <see cref="Rune.ReplacementChar"/>.
/// </summary>
public static VirtualChar Create(char surrogateChar, TextSpan span)
{
if (!char.IsSurrogate(surrogateChar))
throw new ArgumentException(nameof(surrogateChar));
return new VirtualChar(rune: Rune.ReplacementChar, surrogateChar, span);
}
private VirtualChar(Rune rune, char surrogateChar, TextSpan span)
{
Contract.ThrowIfFalse(surrogateChar == 0 || rune == Rune.ReplacementChar,
"If surrogateChar is provided then rune must be Rune.ReplacementChar");
if (span.IsEmpty)
throw new ArgumentException("Span should not be empty.", nameof(span));
Rune = rune;
SurrogateChar = surrogateChar;
Span = span;
}
/// <summary>
/// Retrieves the scaler value of this character as an <see cref="int"/>. If this is an unpaired surrogate
/// character, this will be the value of that surrogate. Otherwise, this will be the value of our <see
/// cref="Rune"/>.
/// </summary>
public int Value => SurrogateChar != 0 ? SurrogateChar : Rune.Value;
#region equality
public static bool operator ==(VirtualChar char1, VirtualChar char2)
=> char1.Equals(char2);
public static bool operator !=(VirtualChar char1, VirtualChar char2)
=> !(char1 == char2);
public static bool operator ==(VirtualChar ch1, char ch2)
=> ch1.Value == ch2;
public static bool operator !=(VirtualChar ch1, char ch2)
=> !(ch1 == ch2);
public override bool Equals(object? obj)
=> obj is VirtualChar vc && Equals(vc);
public bool Equals(VirtualChar other)
=> Rune == other.Rune &&
SurrogateChar == other.SurrogateChar &&
Span == other.Span;
public override int GetHashCode()
{
var hashCode = 1985253839;
hashCode = hashCode * -1521134295 + Rune.GetHashCode();
hashCode = hashCode * -1521134295 + SurrogateChar.GetHashCode();
hashCode = hashCode * -1521134295 + Span.GetHashCode();
return hashCode;
}
#endregion
#region string operations
public override string ToString()
=> SurrogateChar != 0 ? SurrogateChar.ToString() : Rune.ToString();
public void AppendTo(StringBuilder builder)
{
if (SurrogateChar != 0)
{
builder.Append(SurrogateChar);
return;
}
Span<char> chars = stackalloc char[2];
var length = Rune.EncodeToUtf16(chars);
builder.Append(chars[0]);
if (length == 2)
builder.Append(chars[1]);
}
#endregion
#region comparable
public int CompareTo(VirtualChar other)
=> this.Value - other.Value;
public static bool operator <(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value < ch2.Value;
public static bool operator <=(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value <= ch2.Value;
public static bool operator >(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value > ch2.Value;
public static bool operator >=(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value >= ch2.Value;
public int CompareTo(char other)
=> this.Value - other;
public static bool operator <(VirtualChar ch1, char ch2)
=> ch1.Value < ch2;
public static bool operator <=(VirtualChar ch1, char ch2)
=> ch1.Value <= ch2;
public static bool operator >(VirtualChar ch1, char ch2)
=> ch1.Value > ch2;
public static bool operator >=(VirtualChar ch1, char ch2)
=> ch1.Value >= ch2;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars
{
/// <summary>
/// <see cref="VirtualChar"/> provides a uniform view of a language's string token characters regardless if they
/// were written raw in source, or are the production of a language escape sequence. For example, in C#, in a
/// normal <c>""</c> string a <c>Tab</c> character can be written either as the raw tab character (value <c>9</c> in
/// ASCII), or as <c>\t</c>. The format is a single character in the source, while the latter is two characters
/// (<c>\</c> and <c>t</c>). <see cref="VirtualChar"/> will represent both, providing the raw <see cref="char"/>
/// value of <c>9</c> as well as what <see cref="TextSpan"/> in the original <see cref="SourceText"/> they occupied.
/// </summary>
/// <remarks>
/// A core consumer of this system is the Regex parser. That parser wants to work over an array of characters,
/// however this array of characters is not the same as the array of characters a user types into a string in C# or
/// VB. For example In C# someone may write: @"\z". This should appear to the user the same as if they wrote "\\z"
/// and the same as "\\\u007a". However, as these all have wildly different presentations for the user, there needs
/// to be a way to map back the characters it sees ( '\' and 'z' ) back to the ranges of characters the user wrote.
/// </remarks>
internal readonly struct VirtualChar : IEquatable<VirtualChar>, IComparable<VirtualChar>, IComparable<char>
{
/// <summary>
/// The value of this <see cref="VirtualChar"/> as a <see cref="Rune"/> if such a represention is possible.
/// <see cref="Rune"/>s can represent Unicode codepoints that can appear in a <see cref="string"/> except for
/// unpaired surrogates. If an unpaired high or low surrogate character is present, this value will be <see
/// cref="Rune.ReplacementChar"/>. The value of this character can be retrieved from
/// <see cref="SurrogateChar"/>.
/// </summary>
public readonly Rune Rune;
/// <summary>
/// The unpaired high or low surrogate character that was encountered that could not be represented in <see
/// cref="Rune"/>. If <see cref="Rune"/> is not <see cref="Rune.ReplacementChar"/>, this will be <c>0</c>.
/// </summary>
public readonly char SurrogateChar;
/// <summary>
/// The span of characters in the original <see cref="SourceText"/> that represent this <see
/// cref="VirtualChar"/>.
/// </summary>
public readonly TextSpan Span;
/// <summary>
/// Creates a new <see cref="VirtualChar"/> from the provided <paramref name="rune"/>. This operation cannot
/// fail.
/// </summary>
public static VirtualChar Create(Rune rune, TextSpan span)
=> new(rune, surrogateChar: default, span);
/// <summary>
/// Creates a new <see cref="VirtualChar"/> from an unpaired high or low surrogate character. This will throw
/// if <paramref name="surrogateChar"/> is not actually a surrogate character. The resultant <see cref="Rune"/>
/// value will be <see cref="Rune.ReplacementChar"/>.
/// </summary>
public static VirtualChar Create(char surrogateChar, TextSpan span)
{
if (!char.IsSurrogate(surrogateChar))
throw new ArgumentException(nameof(surrogateChar));
return new VirtualChar(rune: Rune.ReplacementChar, surrogateChar, span);
}
private VirtualChar(Rune rune, char surrogateChar, TextSpan span)
{
Contract.ThrowIfFalse(surrogateChar == 0 || rune == Rune.ReplacementChar,
"If surrogateChar is provided then rune must be Rune.ReplacementChar");
if (span.IsEmpty)
throw new ArgumentException("Span should not be empty.", nameof(span));
Rune = rune;
SurrogateChar = surrogateChar;
Span = span;
}
/// <summary>
/// Retrieves the scaler value of this character as an <see cref="int"/>. If this is an unpaired surrogate
/// character, this will be the value of that surrogate. Otherwise, this will be the value of our <see
/// cref="Rune"/>.
/// </summary>
public int Value => SurrogateChar != 0 ? SurrogateChar : Rune.Value;
#region equality
public static bool operator ==(VirtualChar char1, VirtualChar char2)
=> char1.Equals(char2);
public static bool operator !=(VirtualChar char1, VirtualChar char2)
=> !(char1 == char2);
public static bool operator ==(VirtualChar ch1, char ch2)
=> ch1.Value == ch2;
public static bool operator !=(VirtualChar ch1, char ch2)
=> !(ch1 == ch2);
public override bool Equals(object? obj)
=> obj is VirtualChar vc && Equals(vc);
public bool Equals(VirtualChar other)
=> Rune == other.Rune &&
SurrogateChar == other.SurrogateChar &&
Span == other.Span;
public override int GetHashCode()
{
var hashCode = 1985253839;
hashCode = hashCode * -1521134295 + Rune.GetHashCode();
hashCode = hashCode * -1521134295 + SurrogateChar.GetHashCode();
hashCode = hashCode * -1521134295 + Span.GetHashCode();
return hashCode;
}
#endregion
#region string operations
public override string ToString()
=> SurrogateChar != 0 ? SurrogateChar.ToString() : Rune.ToString();
public void AppendTo(StringBuilder builder)
{
if (SurrogateChar != 0)
{
builder.Append(SurrogateChar);
return;
}
Span<char> chars = stackalloc char[2];
var length = Rune.EncodeToUtf16(chars);
builder.Append(chars[0]);
if (length == 2)
builder.Append(chars[1]);
}
#endregion
#region comparable
public int CompareTo(VirtualChar other)
=> this.Value - other.Value;
public static bool operator <(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value < ch2.Value;
public static bool operator <=(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value <= ch2.Value;
public static bool operator >(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value > ch2.Value;
public static bool operator >=(VirtualChar ch1, VirtualChar ch2)
=> ch1.Value >= ch2.Value;
public int CompareTo(char other)
=> this.Value - other;
public static bool operator <(VirtualChar ch1, char ch2)
=> ch1.Value < ch2;
public static bool operator <=(VirtualChar ch1, char ch2)
=> ch1.Value <= ch2;
public static bool operator >(VirtualChar ch1, char ch2)
=> ch1.Value > ch2;
public static bool operator >=(VirtualChar ch1, char ch2)
=> ch1.Value >= ch2;
#endregion
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.cs.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../WorkspaceMSBuildResources.resx">
<body>
<trans-unit id="Failed_to_load_solution_filter_0">
<source>Failed to load solution filter: '{0}'</source>
<target state="translated">Nepovedlo se načíst filtr řešení: {0}</target>
<note />
</trans-unit>
<trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0">
<source>Found project reference without a matching metadata reference: {0}</source>
<target state="translated">Našel se odkaz na projekt bez odpovídajícího odkazu na metadata: {0}</target>
<note />
</trans-unit>
<trans-unit id="Invalid_0_specified_1">
<source>Invalid {0} specified: {1}</source>
<target state="translated">Neplatné zadané {0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0">
<source>Msbuild failed when processing the file '{0}'</source>
<target state="translated">Při zpracovávání souboru {0} došlo k chybě MSBuildu.</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1">
<source>Msbuild failed when processing the file '{0}' with message: {1}</source>
<target state="translated">Při zpracovávání souboru {0} došlo k chybě MSBuildu s touto zprávou: {1}</target>
<note />
</trans-unit>
<trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace">
<source>Parameter cannot be null, empty, or contain whitespace.</source>
<target state="translated">Parametr nemůže být null, prázdný nebo obsahovat prázdné znaky.</target>
<note />
</trans-unit>
<trans-unit id="Path_for_additional_document_0_was_null">
<source>Path for additional document '{0}' was null}</source>
<target state="translated">Cesta k dalšímu dokumentu {0} byla null}</target>
<note />
</trans-unit>
<trans-unit id="Path_for_document_0_was_null">
<source>Path for document '{0}' was null</source>
<target state="translated">Cesta pro dokument {0} byla null.</target>
<note />
</trans-unit>
<trans-unit id="Project_already_added">
<source>Project already added.</source>
<target state="translated">Projekt se už přidal.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_0_target">
<source>Project does not contain '{0}' target.</source>
<target state="translated">Projekt neobsahuje cíl {0}.</target>
<note />
</trans-unit>
<trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0">
<source>Found project with the same file path and output path as another project: {0}</source>
<target state="translated">Byl nalezen projekt, který má stejnou cestu k souboru a výstupní cestu jako jiný projekt: {0}</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_project_discovered_and_skipped_0">
<source>Duplicate project discovered and skipped: {0}</source>
<target state="translated">Byl zjištěn a vynechán duplicitní projekt: {0}</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_have_a_path">
<source>Project does not have a path.</source>
<target state="translated">Projekt nemá cestu.</target>
<note />
</trans-unit>
<trans-unit id="Project_path_for_0_was_null">
<source>Project path for '{0}' was null</source>
<target state="translated">Cesta projektu pro {0} byla null.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_add_metadata_reference_0">
<source>Unable to add metadata reference '{0}'</source>
<target state="translated">Nedá se přidat odkaz na metadata {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_0">
<source>Unable to find '{0}'</source>
<target state="translated">Nedá se najít {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_a_0_for_1">
<source>Unable to find a '{0}' for '{1}'</source>
<target state="translated">Nedá se najít {0} pro {1}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_remove_metadata_reference_0">
<source>Unable to remove metadata reference '{0}'</source>
<target state="translated">Nedá se odebrat odkaz na metadata {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unresolved_metadata_reference_removed_from_project_0">
<source>Unresolved metadata reference removed from project: {0}</source>
<target state="translated">Nevyřešený odkaz na metadata se odebral z projektu: {0}.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../WorkspaceMSBuildResources.resx">
<body>
<trans-unit id="Failed_to_load_solution_filter_0">
<source>Failed to load solution filter: '{0}'</source>
<target state="translated">Nepovedlo se načíst filtr řešení: {0}</target>
<note />
</trans-unit>
<trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0">
<source>Found project reference without a matching metadata reference: {0}</source>
<target state="translated">Našel se odkaz na projekt bez odpovídajícího odkazu na metadata: {0}</target>
<note />
</trans-unit>
<trans-unit id="Invalid_0_specified_1">
<source>Invalid {0} specified: {1}</source>
<target state="translated">Neplatné zadané {0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0">
<source>Msbuild failed when processing the file '{0}'</source>
<target state="translated">Při zpracovávání souboru {0} došlo k chybě MSBuildu.</target>
<note />
</trans-unit>
<trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1">
<source>Msbuild failed when processing the file '{0}' with message: {1}</source>
<target state="translated">Při zpracovávání souboru {0} došlo k chybě MSBuildu s touto zprávou: {1}</target>
<note />
</trans-unit>
<trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace">
<source>Parameter cannot be null, empty, or contain whitespace.</source>
<target state="translated">Parametr nemůže být null, prázdný nebo obsahovat prázdné znaky.</target>
<note />
</trans-unit>
<trans-unit id="Path_for_additional_document_0_was_null">
<source>Path for additional document '{0}' was null}</source>
<target state="translated">Cesta k dalšímu dokumentu {0} byla null}</target>
<note />
</trans-unit>
<trans-unit id="Path_for_document_0_was_null">
<source>Path for document '{0}' was null</source>
<target state="translated">Cesta pro dokument {0} byla null.</target>
<note />
</trans-unit>
<trans-unit id="Project_already_added">
<source>Project already added.</source>
<target state="translated">Projekt se už přidal.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_0_target">
<source>Project does not contain '{0}' target.</source>
<target state="translated">Projekt neobsahuje cíl {0}.</target>
<note />
</trans-unit>
<trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0">
<source>Found project with the same file path and output path as another project: {0}</source>
<target state="translated">Byl nalezen projekt, který má stejnou cestu k souboru a výstupní cestu jako jiný projekt: {0}</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_project_discovered_and_skipped_0">
<source>Duplicate project discovered and skipped: {0}</source>
<target state="translated">Byl zjištěn a vynechán duplicitní projekt: {0}</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_have_a_path">
<source>Project does not have a path.</source>
<target state="translated">Projekt nemá cestu.</target>
<note />
</trans-unit>
<trans-unit id="Project_path_for_0_was_null">
<source>Project path for '{0}' was null</source>
<target state="translated">Cesta projektu pro {0} byla null.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_add_metadata_reference_0">
<source>Unable to add metadata reference '{0}'</source>
<target state="translated">Nedá se přidat odkaz na metadata {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_0">
<source>Unable to find '{0}'</source>
<target state="translated">Nedá se najít {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_find_a_0_for_1">
<source>Unable to find a '{0}' for '{1}'</source>
<target state="translated">Nedá se najít {0} pro {1}.</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_remove_metadata_reference_0">
<source>Unable to remove metadata reference '{0}'</source>
<target state="translated">Nedá se odebrat odkaz na metadata {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unresolved_metadata_reference_removed_from_project_0">
<source>Unresolved metadata reference removed from project: {0}</source>
<target state="translated">Nevyřešený odkaz na metadata se odebral z projektu: {0}.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/FromKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions
''' <summary>
''' Recommends the "From" keyword when used in a New syntax (such as New goo From)
''' </summary>
Friend Class FromKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("From", VBFeaturesResources.Identifies_a_list_of_values_as_a_collection_initializer))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsFollowingCompleteAsNewClause() OrElse
targetToken.IsFollowingCompleteObjectCreation() Then
Dim objectCreation = targetToken.GetAncestor(Of ObjectCreationExpressionSyntax)()
Dim type = TryCast(context.SemanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol, ITypeSymbol)
Dim enclosingSymbol = context.SemanticModel.GetEnclosingNamedTypeOrAssembly(context.Position, cancellationToken)
If type IsNot Nothing AndAlso type.CanSupportCollectionInitializer(enclosingSymbol) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions
''' <summary>
''' Recommends the "From" keyword when used in a New syntax (such as New goo From)
''' </summary>
Friend Class FromKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("From", VBFeaturesResources.Identifies_a_list_of_values_as_a_collection_initializer))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsFollowingCompleteAsNewClause() OrElse
targetToken.IsFollowingCompleteObjectCreation() Then
Dim objectCreation = targetToken.GetAncestor(Of ObjectCreationExpressionSyntax)()
Dim type = TryCast(context.SemanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol, ITypeSymbol)
Dim enclosingSymbol = context.SemanticModel.GetEnclosingNamedTypeOrAssembly(context.Position, cancellationToken)
If type IsNot Nothing AndAlso type.CanSupportCollectionInitializer(enclosingSymbol) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Portable/Emitter/NoPia/EmbeddedType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
#if !DEBUG
using NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol;
using FieldSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol;
using MethodSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol;
using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol;
using PropertySymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol;
#endif
namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia
{
internal sealed class EmbeddedType : EmbeddedTypesManager.CommonEmbeddedType
{
private bool _embeddedAllMembersOfImplementedInterface;
public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbolAdapter underlyingNamedType) :
base(typeManager, underlyingNamedType)
{
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsDefinition);
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsTopLevelType());
Debug.Assert(!underlyingNamedType.AdaptedNamedTypeSymbol.IsGenericType);
}
public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType());
if (_embeddedAllMembersOfImplementedInterface)
{
return;
}
_embeddedAllMembersOfImplementedInterface = true;
// Embed all members
foreach (MethodSymbol m in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit())
{
if ((object)m != null)
{
TypeManager.EmbedMethod(this, m.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
}
// We also should embed properties and events, but we don't need to do this explicitly here
// because accessors embed them automatically.
// Do the same for implemented interfaces.
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true);
}
}
protected override int GetAssemblyRefIndex()
{
ImmutableArray<AssemblySymbol> refs = TypeManager.ModuleBeingBuilt.SourceModule.GetReferencedAssemblySymbols();
return refs.IndexOf(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, ReferenceEqualityComparer.Instance);
}
protected override bool IsPublic
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == Accessibility.Public;
}
}
protected override Cci.ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
NamedTypeSymbol baseType = UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
return (object)baseType != null ? moduleBuilder.Translate(baseType, syntaxNodeOpt, diagnostics) : null;
}
protected override IEnumerable<FieldSymbolAdapter> GetFieldsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<MethodSymbolAdapter> GetMethodsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()
#if DEBUG
.Select(s => s?.GetCciAdapter())
#endif
;
}
protected override IEnumerable<EventSymbolAdapter> GetEventsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<PropertySymbolAdapter> GetPropertiesToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context)
{
Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module);
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
var typeRef = moduleBeingBuilt.Translate(
@interface,
(CSharpSyntaxNode)context.SyntaxNode,
context.Diagnostics);
var type = TypeWithAnnotations.Create(@interface);
yield return type.GetTypeRefWithAttributes(
moduleBeingBuilt,
declaringSymbol: UnderlyingNamedType.AdaptedNamedTypeSymbol,
typeRef);
}
}
protected override bool IsAbstract
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract;
}
}
protected override bool IsBeforeFieldInit
{
get
{
switch (UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind)
{
case TypeKind.Enum:
case TypeKind.Delegate:
//C# interfaces don't have fields so the flag doesn't really matter, but Dev10 omits it
case TypeKind.Interface:
return false;
}
// We shouldn't embed static constructor.
return true;
}
}
protected override bool IsComImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport;
}
}
protected override bool IsInterface
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType();
}
}
protected override bool IsDelegate
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType();
}
}
protected override bool IsSerializable
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable;
}
}
protected override bool IsSpecialName
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName;
}
}
protected override bool IsWindowsRuntimeImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport;
}
}
protected override bool IsSealed
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed;
}
}
protected override TypeLayout? GetTypeLayoutIfStruct()
{
if (UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType())
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout;
}
return null;
}
protected override System.Runtime.InteropServices.CharSet StringFormat
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet;
}
}
protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder);
}
protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var member = hasGuid ?
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctor :
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString;
var ctor = TypeManager.GetWellKnownMethod(member, syntaxNodeOpt, diagnostics);
if ((object)ctor == null)
{
return null;
}
if (hasGuid)
{
// This is an interface with a GuidAttribute, so we will generate the no-parameter TypeIdentifier.
return new SynthesizedAttributeData(ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
else
{
// This is an interface with no GuidAttribute, or some other type, so we will generate the
// TypeIdentifier with name and scope parameters.
// Look for a GUID attribute attached to type's containing assembly. If we find one, we'll use it;
// otherwise, we expect that we will have reported an error (ERRID_PIAHasNoAssemblyGuid1) about this assembly, since
// you can't /link against an assembly which lacks a GuidAttribute.
var stringType = TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics);
if ((object)stringType != null)
{
string guidString = TypeManager.GetAssemblyGuidString(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly);
return new SynthesizedAttributeData(ctor,
ImmutableArray.Create(new TypedConstant(stringType, TypedConstantKind.Primitive, guidString),
new TypedConstant(stringType, TypedConstantKind.Primitive,
UnderlyingNamedType.AdaptedNamedTypeSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))),
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
}
return null;
}
protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, UnderlyingNamedType.AdaptedNamedTypeSymbol, description.FullName);
}
protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
foreach (Symbol s in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember))
{
switch (s.Kind)
{
case SymbolKind.Field:
TypeManager.EmbedField(this, ((FieldSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Method:
TypeManager.EmbedMethod(this, ((MethodSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Property:
TypeManager.EmbedProperty(this, ((PropertySymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Event:
TypeManager.EmbedEvent(this, ((EventSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false);
break;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
#if !DEBUG
using NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol;
using FieldSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol;
using MethodSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol;
using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol;
using PropertySymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol;
#endif
namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia
{
internal sealed class EmbeddedType : EmbeddedTypesManager.CommonEmbeddedType
{
private bool _embeddedAllMembersOfImplementedInterface;
public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbolAdapter underlyingNamedType) :
base(typeManager, underlyingNamedType)
{
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsDefinition);
Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsTopLevelType());
Debug.Assert(!underlyingNamedType.AdaptedNamedTypeSymbol.IsGenericType);
}
public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType());
if (_embeddedAllMembersOfImplementedInterface)
{
return;
}
_embeddedAllMembersOfImplementedInterface = true;
// Embed all members
foreach (MethodSymbol m in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit())
{
if ((object)m != null)
{
TypeManager.EmbedMethod(this, m.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
}
// We also should embed properties and events, but we don't need to do this explicitly here
// because accessors embed them automatically.
// Do the same for implemented interfaces.
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true);
}
}
protected override int GetAssemblyRefIndex()
{
ImmutableArray<AssemblySymbol> refs = TypeManager.ModuleBeingBuilt.SourceModule.GetReferencedAssemblySymbols();
return refs.IndexOf(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, ReferenceEqualityComparer.Instance);
}
protected override bool IsPublic
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == Accessibility.Public;
}
}
protected override Cci.ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
NamedTypeSymbol baseType = UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
return (object)baseType != null ? moduleBuilder.Translate(baseType, syntaxNodeOpt, diagnostics) : null;
}
protected override IEnumerable<FieldSymbolAdapter> GetFieldsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<MethodSymbolAdapter> GetMethodsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()
#if DEBUG
.Select(s => s?.GetCciAdapter())
#endif
;
}
protected override IEnumerable<EventSymbolAdapter> GetEventsToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<PropertySymbolAdapter> GetPropertiesToEmit()
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit()
#if DEBUG
.Select(s => s.GetCciAdapter())
#endif
;
}
protected override IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context)
{
Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module);
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit())
{
var typeRef = moduleBeingBuilt.Translate(
@interface,
(CSharpSyntaxNode)context.SyntaxNode,
context.Diagnostics);
var type = TypeWithAnnotations.Create(@interface);
yield return type.GetTypeRefWithAttributes(
moduleBeingBuilt,
declaringSymbol: UnderlyingNamedType.AdaptedNamedTypeSymbol,
typeRef);
}
}
protected override bool IsAbstract
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract;
}
}
protected override bool IsBeforeFieldInit
{
get
{
switch (UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind)
{
case TypeKind.Enum:
case TypeKind.Delegate:
//C# interfaces don't have fields so the flag doesn't really matter, but Dev10 omits it
case TypeKind.Interface:
return false;
}
// We shouldn't embed static constructor.
return true;
}
}
protected override bool IsComImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport;
}
}
protected override bool IsInterface
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType();
}
}
protected override bool IsDelegate
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType();
}
}
protected override bool IsSerializable
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable;
}
}
protected override bool IsSpecialName
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName;
}
}
protected override bool IsWindowsRuntimeImport
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport;
}
}
protected override bool IsSealed
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed;
}
}
protected override TypeLayout? GetTypeLayoutIfStruct()
{
if (UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType())
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout;
}
return null;
}
protected override System.Runtime.InteropServices.CharSet StringFormat
{
get
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet;
}
}
protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder);
}
protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var member = hasGuid ?
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctor :
WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString;
var ctor = TypeManager.GetWellKnownMethod(member, syntaxNodeOpt, diagnostics);
if ((object)ctor == null)
{
return null;
}
if (hasGuid)
{
// This is an interface with a GuidAttribute, so we will generate the no-parameter TypeIdentifier.
return new SynthesizedAttributeData(ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
else
{
// This is an interface with no GuidAttribute, or some other type, so we will generate the
// TypeIdentifier with name and scope parameters.
// Look for a GUID attribute attached to type's containing assembly. If we find one, we'll use it;
// otherwise, we expect that we will have reported an error (ERRID_PIAHasNoAssemblyGuid1) about this assembly, since
// you can't /link against an assembly which lacks a GuidAttribute.
var stringType = TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics);
if ((object)stringType != null)
{
string guidString = TypeManager.GetAssemblyGuidString(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly);
return new SynthesizedAttributeData(ctor,
ImmutableArray.Create(new TypedConstant(stringType, TypedConstantKind.Primitive, guidString),
new TypedConstant(stringType, TypedConstantKind.Primitive,
UnderlyingNamedType.AdaptedNamedTypeSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))),
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
}
return null;
}
protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, UnderlyingNamedType.AdaptedNamedTypeSymbol, description.FullName);
}
protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
foreach (Symbol s in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember))
{
switch (s.Kind)
{
case SymbolKind.Field:
TypeManager.EmbedField(this, ((FieldSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Method:
TypeManager.EmbedMethod(this, ((MethodSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Property:
TypeManager.EmbedProperty(this, ((PropertySymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics);
break;
case SymbolKind.Event:
TypeManager.EmbedEvent(this, ((EventSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false);
break;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/Core/Portable/ExternalAccess/Razor/Api/IRazorDocumentOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api
{
internal interface IRazorDocumentOptions
{
bool TryGetDocumentOption(OptionKey option, out object? value);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api
{
internal interface IRazorDocumentOptions
{
bool TryGetDocumentOption(OptionKey option, out object? value);
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.UseCollectionInitializer
{
internal abstract partial class AbstractUseCollectionInitializerDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TInvocationExpressionSyntax,
TExpressionStatementSyntax,
TVariableDeclaratorSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TInvocationExpressionSyntax : TExpressionSyntax
where TExpressionStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected AbstractUseCollectionInitializerDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseCollectionInitializerDiagnosticId,
EnforceOnBuildValues.UseCollectionInitializer,
CodeStyleOptions2.PreferCollectionInitializer,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_collection_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Collection_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterCompilationStartAction(OnCompilationStart);
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
if (!AreCollectionInitializersSupported(context.Compilation))
{
return;
}
var ienumerableType = context.Compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName!);
if (ienumerableType != null)
{
var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
context.RegisterSyntaxNodeAction(
nodeContext => AnalyzeNode(nodeContext, ienumerableType),
syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression));
}
}
protected abstract bool AreCollectionInitializersSupported(Compilation compilation);
private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ienumerableType)
{
var semanticModel = context.SemanticModel;
var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node;
var language = objectCreationExpression.Language;
var cancellationToken = context.CancellationToken;
var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language);
if (!option.Value)
{
// not point in analyzing if the option is off.
return;
}
// Object creation can only be converted to collection initializer if it
// implements the IEnumerable type.
var objectType = context.SemanticModel.GetTypeInfo(objectCreationExpression, cancellationToken);
if (objectType.Type == null || !objectType.Type.AllInterfaces.Contains(ienumerableType))
{
return;
}
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
semanticModel, GetSyntaxFacts(), objectCreationExpression, cancellationToken);
if (matches == null || matches.Value.Length == 0)
{
return;
}
var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (containingStatement == null)
{
return;
}
var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value);
var syntaxFacts = GetSyntaxFacts();
if (syntaxFacts.ContainsInterleavedDirective(nodes, cancellationToken))
{
return;
}
var locations = ImmutableArray.Create(objectCreationExpression.GetLocation());
var severity = option.Notification.Severity;
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreationExpression.GetLocation(),
severity,
additionalLocations: locations,
properties: null));
FadeOutCode(context, matches.Value, locations);
}
private void FadeOutCode(
SyntaxNodeAnalysisContext context,
ImmutableArray<TExpressionStatementSyntax> matches,
ImmutableArray<Location> locations)
{
var syntaxTree = context.Node.SyntaxTree;
var fadeOutCode = context.GetOption(
CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language);
if (!fadeOutCode)
{
return;
}
var syntaxFacts = GetSyntaxFacts();
foreach (var match in matches)
{
var expression = syntaxFacts.GetExpressionOfExpressionStatement(match);
if (syntaxFacts.IsInvocationExpression(expression))
{
var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(expression);
var additionalUnnecessaryLocations = ImmutableArray.Create(
syntaxTree.GetLocation(TextSpan.FromBounds(match.SpanStart, arguments[0].SpanStart)),
syntaxTree.GetLocation(TextSpan.FromBounds(arguments.Last().FullSpan.End, match.Span.End)));
// Report the diagnostic at the first unnecessary location. This is the location where the code fix
// will be offered.
var location1 = additionalUnnecessaryLocations[0];
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
location1,
ReportDiagnostic.Default,
additionalLocations: locations,
additionalUnnecessaryLocations: additionalUnnecessaryLocations));
}
}
}
protected abstract ISyntaxFacts GetSyntaxFacts();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.UseCollectionInitializer
{
internal abstract partial class AbstractUseCollectionInitializerDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TInvocationExpressionSyntax,
TExpressionStatementSyntax,
TVariableDeclaratorSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TInvocationExpressionSyntax : TExpressionSyntax
where TExpressionStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected AbstractUseCollectionInitializerDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseCollectionInitializerDiagnosticId,
EnforceOnBuildValues.UseCollectionInitializer,
CodeStyleOptions2.PreferCollectionInitializer,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_collection_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Collection_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterCompilationStartAction(OnCompilationStart);
private void OnCompilationStart(CompilationStartAnalysisContext context)
{
if (!AreCollectionInitializersSupported(context.Compilation))
{
return;
}
var ienumerableType = context.Compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName!);
if (ienumerableType != null)
{
var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
context.RegisterSyntaxNodeAction(
nodeContext => AnalyzeNode(nodeContext, ienumerableType),
syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression));
}
}
protected abstract bool AreCollectionInitializersSupported(Compilation compilation);
private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ienumerableType)
{
var semanticModel = context.SemanticModel;
var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node;
var language = objectCreationExpression.Language;
var cancellationToken = context.CancellationToken;
var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language);
if (!option.Value)
{
// not point in analyzing if the option is off.
return;
}
// Object creation can only be converted to collection initializer if it
// implements the IEnumerable type.
var objectType = context.SemanticModel.GetTypeInfo(objectCreationExpression, cancellationToken);
if (objectType.Type == null || !objectType.Type.AllInterfaces.Contains(ienumerableType))
{
return;
}
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TInvocationExpressionSyntax, TExpressionStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
semanticModel, GetSyntaxFacts(), objectCreationExpression, cancellationToken);
if (matches == null || matches.Value.Length == 0)
{
return;
}
var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (containingStatement == null)
{
return;
}
var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value);
var syntaxFacts = GetSyntaxFacts();
if (syntaxFacts.ContainsInterleavedDirective(nodes, cancellationToken))
{
return;
}
var locations = ImmutableArray.Create(objectCreationExpression.GetLocation());
var severity = option.Notification.Severity;
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreationExpression.GetLocation(),
severity,
additionalLocations: locations,
properties: null));
FadeOutCode(context, matches.Value, locations);
}
private void FadeOutCode(
SyntaxNodeAnalysisContext context,
ImmutableArray<TExpressionStatementSyntax> matches,
ImmutableArray<Location> locations)
{
var syntaxTree = context.Node.SyntaxTree;
var fadeOutCode = context.GetOption(
CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language);
if (!fadeOutCode)
{
return;
}
var syntaxFacts = GetSyntaxFacts();
foreach (var match in matches)
{
var expression = syntaxFacts.GetExpressionOfExpressionStatement(match);
if (syntaxFacts.IsInvocationExpression(expression))
{
var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(expression);
var additionalUnnecessaryLocations = ImmutableArray.Create(
syntaxTree.GetLocation(TextSpan.FromBounds(match.SpanStart, arguments[0].SpanStart)),
syntaxTree.GetLocation(TextSpan.FromBounds(arguments.Last().FullSpan.End, match.Span.End)));
// Report the diagnostic at the first unnecessary location. This is the location where the code fix
// will be offered.
var location1 = additionalUnnecessaryLocations[0];
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
location1,
ReportDiagnostic.Default,
additionalLocations: locations,
additionalUnnecessaryLocations: additionalUnnecessaryLocations));
}
}
}
protected abstract ISyntaxFacts GetSyntaxFacts();
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Core/Portable/IVTConclusion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The result of <see cref="ISymbolExtensions.PerformIVTCheck(AssemblyIdentity, ImmutableArray{byte}, ImmutableArray{byte})"/>
/// </summary>
internal enum IVTConclusion
{
/// <summary>
/// This indicates that friend access should be granted.
/// </summary>
Match,
/// <summary>
/// This indicates that friend access should be granted for the purposes of error recovery,
/// but the program is wrong.
///
/// That's because this indicates that a strong-named assembly has referred to a weak-named assembly
/// which has extended friend access to the strong-named assembly. This will ultimately
/// result in an error because strong-named assemblies may not refer to weak-named assemblies.
/// In Roslyn we give a new error, CS7029, before emit time. In the dev10 compiler we error at
/// emit time.
/// </summary>
OneSignedOneNot,
/// <summary>
/// This indicates that friend access should not be granted because the other assembly grants
/// friend access to a strong-named assembly, and either this assembly is weak-named, or
/// it is strong-named and the names don't match.
/// </summary>
PublicKeyDoesntMatch,
/// <summary>
/// This indicates that friend access should not be granted because the other assembly
/// does not name this assembly as a friend in any way whatsoever.
/// </summary>
NoRelationshipClaimed
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The result of <see cref="ISymbolExtensions.PerformIVTCheck(AssemblyIdentity, ImmutableArray{byte}, ImmutableArray{byte})"/>
/// </summary>
internal enum IVTConclusion
{
/// <summary>
/// This indicates that friend access should be granted.
/// </summary>
Match,
/// <summary>
/// This indicates that friend access should be granted for the purposes of error recovery,
/// but the program is wrong.
///
/// That's because this indicates that a strong-named assembly has referred to a weak-named assembly
/// which has extended friend access to the strong-named assembly. This will ultimately
/// result in an error because strong-named assemblies may not refer to weak-named assemblies.
/// In Roslyn we give a new error, CS7029, before emit time. In the dev10 compiler we error at
/// emit time.
/// </summary>
OneSignedOneNot,
/// <summary>
/// This indicates that friend access should not be granted because the other assembly grants
/// friend access to a strong-named assembly, and either this assembly is weak-named, or
/// it is strong-named and the names don't match.
/// </summary>
PublicKeyDoesntMatch,
/// <summary>
/// This indicates that friend access should not be granted because the other assembly
/// does not name this assembly as a friend in any way whatsoever.
/// </summary>
NoRelationshipClaimed
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<PackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.NewNameSinceWeReferenceTheAnalyzersAndNuGetCannotFigureItOut</PackageId>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\DefaultOperationProvider.vb" Link="Formatting\DefaultOperationProvider.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\AggregatedFormattingResult.vb" Link="Formatting\Engine\AggregatedFormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\FormattingResult.vb" Link="Formatting\Engine\FormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" Link="Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicFormatEngine.vb" Link="Formatting\Engine\VisualBasicFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" Link="Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\FormattingHelpers.vb" Link="Formatting\FormattingHelpers.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AdjustSpaceFormattingRule.vb" Link="Formatting\Rules\AdjustSpaceFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AlignTokensFormattingRule.vb" Link="Formatting\Rules\AlignTokensFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\BaseFormattingRule.vb" Link="Formatting\Rules\BaseFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\ElasticTriviaFormattingRule.vb" Link="Formatting\Rules\ElasticTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\NodeBasedFormattingRule.vb" Link="Formatting\Rules\NodeBasedFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\StructuredTriviaFormattingRule.vb" Link="Formatting\Rules\StructuredTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\VisualBasicSyntaxFormattingService.vb" Link="Formatting\VisualBasicSyntaxFormattingService.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<PackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.NewNameSinceWeReferenceTheAnalyzersAndNuGetCannotFigureItOut</PackageId>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\DefaultOperationProvider.vb" Link="Formatting\DefaultOperationProvider.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\AggregatedFormattingResult.vb" Link="Formatting\Engine\AggregatedFormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\FormattingResult.vb" Link="Formatting\Engine\FormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" Link="Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicFormatEngine.vb" Link="Formatting\Engine\VisualBasicFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" Link="Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\FormattingHelpers.vb" Link="Formatting\FormattingHelpers.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AdjustSpaceFormattingRule.vb" Link="Formatting\Rules\AdjustSpaceFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AlignTokensFormattingRule.vb" Link="Formatting\Rules\AlignTokensFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\BaseFormattingRule.vb" Link="Formatting\Rules\BaseFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\ElasticTriviaFormattingRule.vb" Link="Formatting\Rules\ElasticTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\NodeBasedFormattingRule.vb" Link="Formatting\Rules\NodeBasedFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\StructuredTriviaFormattingRule.vb" Link="Formatting\Rules\StructuredTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\VisualBasicSyntaxFormattingService.vb" Link="Formatting\VisualBasicSyntaxFormattingService.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenExpression.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 Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenExpression
Inherits BasicTestBase
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Fix(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Fix(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Fix(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Fix(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Fix(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Fix(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0F, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Fix(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Fix(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Fix(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Fix(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Fix(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Fix(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F) ' overflow
CheckSingle(Integer.MaxValue - 0F) ' overflow
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Fix(number)
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Fix(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Fix(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Fix(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Fix(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Fix(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Fix(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Fix(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Fix(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Fix(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Fix(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Fix(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Fix(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Fix(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Fix(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Fix(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0F, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Fix(number)
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Fix(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Fix(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Fix(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Fix(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Fix(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Fix(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Fix(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Fix(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Fix(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Fix(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Fix(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Fix(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Fix(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Fix(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Fix(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F) ' overflow
CheckSingle(Integer.MaxValue - 0F) ' overflow
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Truncate(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Truncate(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Truncate(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Truncate(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Truncate(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Truncate(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Ceiling(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Ceiling(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Ceiling(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Ceiling(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D) ' overflow
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Ceiling(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Ceiling(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D) ' overflow
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Floor(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Floor(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Floor(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Floor(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Floor(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Floor(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Floor(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Floor(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Floor(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Floor(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Floor(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Floor(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Floor(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Floor(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Floor(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Floor(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Floor(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Floor(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Floor(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Floor(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Floor(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Floor(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Floor(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Floor(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Round(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Round(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Round(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Round(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Round(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Round(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Round(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Round(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Round(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Round(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Round(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Round(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Round(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Round(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Round(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Round(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Round(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Round(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Round(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Round(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Round(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Round(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Round(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Round(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Round(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Round(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Round(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Round(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Round(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Round(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Round(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Round(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Int(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Int(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Int(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Int(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Int(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Int(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Int(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Int(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Int(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Int(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Int(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Int(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Int(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Int(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Int(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Int(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Int(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Int(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Int(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Int(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Int(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Int(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Int(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Int(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Int(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Int(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 60F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 2F, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected & " " & result)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Int(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Int(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Int(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Int(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F) ' overflow
CheckSingle(Integer.MaxValue - 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0F) ' overflow
CheckSingle(Integer.MaxValue + 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0.99F) ' overflow
CheckSingle(Integer.MaxValue + 1F) ' overflow
CheckSingle(Integer.MaxValue + 2F) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Throw New Exception("No exception on " & s & " got " & result)
Catch ex As OverflowException
Return
End Try
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Int(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Int(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Int(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Int(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Int(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Int(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Int(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0.99F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 2F, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Int(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Int(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Int(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Int(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Int(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Int(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Int(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F) ' overflow
CheckSingle(Integer.MaxValue - 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0F) ' overflow
CheckSingle(Integer.MaxValue + 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0.99F) ' overflow
CheckSingle(Integer.MaxValue + 1F) ' overflow
CheckSingle(Integer.MaxValue + 2F) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
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 Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenExpression
Inherits BasicTestBase
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Fix(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Fix(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Fix(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Fix(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Fix(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Fix(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0F, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Fix(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Fix(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Fix(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Fix(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Fix(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Fix(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Fix(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Fix(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Fix(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Fix(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Fix(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F) ' overflow
CheckSingle(Integer.MaxValue - 0F) ' overflow
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Fix(number)
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Fix(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Fix(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Fix(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Fix(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Fix(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Fix(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Fix(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Fix(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Fix(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Fix(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Fix(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Fix(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Fix(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Fix(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Fix(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0F, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFix_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Fix(number)
End Function
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Fix(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Fix(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Fix(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Fix(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Fix(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Fix(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Fix(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Fix(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Fix(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Fix(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Fix(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Fix(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Fix(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Fix(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Fix(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 65F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 64F, Integer.MinValue)
CheckSingle(Integer.MinValue + 65F, -2147483520)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 64F) ' overflow
CheckSingle(Integer.MaxValue - 0F) ' overflow
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Truncate(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Truncate(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Truncate(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Truncate(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Truncate(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Truncate(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Truncate(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Truncate(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntTruncate_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Truncate(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Truncate(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u1
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u2
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u4
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.i8
IL_0002: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.ovf.u8
IL_0002: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Ceiling(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Ceiling(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Ceiling(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Ceiling(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Ceiling(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Ceiling(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Ceiling(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D) ' overflow
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Ceiling(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntCeiling_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Ceiling(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Ceiling(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D) ' overflow
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Ceiling(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Floor(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Floor(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Floor(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Floor(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Floor(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Floor(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Floor(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Floor(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Floor(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Floor(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Floor(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Floor(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Floor(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Floor(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Floor(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Floor(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Floor(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Floor(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Floor(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Floor(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntFloor_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Floor(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Floor(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Floor(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Floor(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Floor(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Floor(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Floor(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Round(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Round(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Round(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Round(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Round(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Round(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Round(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Round(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Math.Round(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Math.Round(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Math.Round(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Math.Round(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Math.Round(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Math.Round(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Math.Round(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Math.Round(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Round(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Round(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Round(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Round(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Round(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Round(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Round(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Round(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<Fact, WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
Public Sub CIntRound_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Math.Round(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Math.Round(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Math.Round(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Math.Round(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Math.Round(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Math.Round(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Math.Round(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Math.Round(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue)
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 2)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D) ' overflow
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Math.Round(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Int(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Int(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Int(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Int(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return CByte(Int(number))
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return CShort(Int(number))
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return CInt(Int(number))
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return CLng(Int(number))
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Int(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Int(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Int(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Int(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Int(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Int(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Int(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue - 0.01D, Integer.MinValue) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D, Integer.MinValue) ' overflow
CheckDouble(Integer.MaxValue + 2D, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function DoubleToSByte(number as Double) As SByte
Return Int(number)
End Function
Public Shared Function DoubleToByte(number as Double) As Byte
Return Int(number)
End Function
Public Shared Function DoubleToShort(number as Double) As Short
Return Int(number)
End Function
Public Shared Function DoubleToUShort(number as Double) As UShort
Return Int(number)
End Function
Public Shared Function DoubleToInteger(number as Double) As Integer
Return Int(number)
End Function
Public Shared Function DoubleToUInteger(number as Double) As UInteger
Return Int(number)
End Function
Public Shared Function DoubleToLong(number as Double) As Long
Return Int(number)
End Function
Public Shared Function DoubleToULong(number as Double) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckDouble(Integer.MinValue - 1D) ' overflow
CheckDouble(Integer.MinValue - 0.01D) ' overflow
CheckDouble(Integer.MinValue + 0D, Integer.MinValue)
CheckDouble(Integer.MinValue + 1D, -2147483647)
CheckDouble(1.99D, 1)
CheckDouble(Integer.MaxValue - 1D, 2147483646)
CheckDouble(Integer.MaxValue - 0.01D, 2147483646)
CheckDouble(Integer.MaxValue + 0D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.01D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 0.99D, Integer.MaxValue)
CheckDouble(Integer.MaxValue + 1D) ' overflow
CheckDouble(Integer.MaxValue + 2D) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckDouble(s As Double, expected As Integer)
Dim result As Integer = DoubleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckDouble(s As Double)
Try
Dim result As Integer = DoubleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.DoubleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.DoubleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Double) As Double"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Int(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Int(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Int(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Int(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 65F, 2147483520)
CheckSingle(Integer.MaxValue - 60F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 2F, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected & " " & result)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_Checked_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return CSByte(Int(number))
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return CByte(Int(number))
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return CShort(Int(number))
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return CUShort(Int(number))
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return CInt(Int(number))
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return CUInt(Int(number))
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return CLng(Int(number))
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return CULng(Int(number))
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F) ' overflow
CheckSingle(Integer.MaxValue - 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0F) ' overflow
CheckSingle(Integer.MaxValue + 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0.99F) ' overflow
CheckSingle(Integer.MaxValue + 1F) ' overflow
CheckSingle(Integer.MaxValue + 2F) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Throw New Exception("No exception on " & s & " got " & result)
Catch ex As OverflowException
Return
End Try
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_Implicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Int(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Int(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Int(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Int(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Int(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Int(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Int(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue - 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0.01F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 0.99F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 1F, Integer.MinValue) ' overflow
CheckSingle(Integer.MaxValue + 2F, Integer.MinValue) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.u8
IL_0007: ret
}
]]>)
End Sub
<WorkItem(25692, "https://github.com/dotnet/roslyn/issues/25692")>
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub CIntInt_Single_CheckedImplicit_01()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Class C1
Public Shared Function SingleToSByte(number as Single) As SByte
Return Int(number)
End Function
Public Shared Function SingleToByte(number as Single) As Byte
Return Int(number)
End Function
Public Shared Function SingleToShort(number as Single) As Short
Return Int(number)
End Function
Public Shared Function SingleToUShort(number as Single) As UShort
Return Int(number)
End Function
Public Shared Function SingleToInteger(number as Single) As Integer
Return Int(number)
End Function
Public Shared Function SingleToUInteger(number as Single) As UInteger
Return Int(number)
End Function
Public Shared Function SingleToLong(number as Single) As Long
Return Int(number)
End Function
Public Shared Function SingleToULong(number as Single) As ULong
Return Int(number)
End Function
Public Shared Sub Main()
CheckSingle(Integer.MinValue - 1F, Integer.MinValue)
CheckSingle(Integer.MinValue - 0.01F, Integer.MinValue)
CheckSingle(Integer.MinValue + 0F, Integer.MinValue)
CheckSingle(Integer.MinValue + 1F, Integer.MinValue)
CheckSingle(1.99F, 1)
CheckSingle(Integer.MaxValue - 1F) ' overflow
CheckSingle(Integer.MaxValue - 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0F) ' overflow
CheckSingle(Integer.MaxValue + 0.01F) ' overflow
CheckSingle(Integer.MaxValue + 0.99F) ' overflow
CheckSingle(Integer.MaxValue + 1F) ' overflow
CheckSingle(Integer.MaxValue + 2F) ' overflow
Console.WriteLine("done")
End Sub
Public Shared Sub CheckSingle(s As Single, expected As Integer)
Dim result As Integer = SingleToInteger(s)
If result <> expected
Throw New Exception("Error on " & s & " " & expected)
End If
End Sub
Public Shared Sub CheckSingle(s As Single)
Try
Dim result As Integer = SingleToInteger(s)
Catch ex As OverflowException
Return
End Try
Throw New Exception("Error on " & s)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
Dim cv = CompileAndVerify(compilation,
expectedOutput:=<![CDATA[
done
]]>)
cv.VerifyIL("C1.SingleToSByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToByte", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u1
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUShort", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u2
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToUInteger", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u4
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToLong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.i8
IL_0007: ret
}
]]>)
cv.VerifyIL("C1.SingleToULong", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.Conversion.Int(Single) As Single"
IL_0006: conv.ovf.u8
IL_0007: ret
}
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Core/Portable/InternalUtilities/Hash.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class Hash
{
/// <summary>
/// This is how VB Anonymous Types combine hash values for fields.
/// </summary>
internal static int Combine(int newKey, int currentKey)
{
return unchecked((currentKey * (int)0xA5555529) + newKey);
}
internal static int Combine(bool newKeyPart, int currentKey)
{
return Combine(currentKey, newKeyPart ? 1 : 0);
}
/// <summary>
/// This is how VB Anonymous Types combine hash values for fields.
/// PERF: Do not use with enum types because that involves multiple
/// unnecessary boxing operations. Unfortunately, we can't constrain
/// T to "non-enum", so we'll use a more restrictive constraint.
/// </summary>
internal static int Combine<T>(T newKeyPart, int currentKey) where T : class?
{
int hash = unchecked(currentKey * (int)0xA5555529);
if (newKeyPart != null)
{
return unchecked(hash + newKeyPart.GetHashCode());
}
return hash;
}
internal static int CombineValues<T>(IEnumerable<T>? values, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues<T>(T[]? values, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var maxSize = Math.Min(maxItemsToHash, values.Length);
var hashCode = 0;
for (int i = 0; i < maxSize; i++)
{
T value = values[i];
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue)
{
if (values.IsDefaultOrEmpty)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues(IEnumerable<string?>? values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
if (value != null)
{
hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode);
}
}
return hashCode;
}
/// <summary>
/// The offset bias value used in the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
internal const int FnvOffsetBias = unchecked((int)2166136261);
/// <summary>
/// The generative factor used in the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
internal const int FnvPrime = 16777619;
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(byte[] data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes and determines if the byte
/// sequence is valid ASCII and hence the hash code matches a char sequence
/// encoding the same text.
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes that are likely to be ASCII text.</param>
/// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(ReadOnlySpan<byte> data, out bool isAscii)
{
int hashCode = Hash.FnvOffsetBias;
byte asciiMask = 0;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
asciiMask |= b;
hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime);
}
isAscii = (asciiMask & 0x80) == 0;
return hashCode;
}
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(ImmutableArray<byte> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here
/// for 16-bit Unicode chars on the understanding that the majority of chars will
/// fit into 8-bits and, therefore, the algorithm will retain its desirable traits
/// for generating hash codes.
/// </summary>
internal static int GetFNVHashCode(ReadOnlySpan<char> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here
/// for 16-bit Unicode chars on the understanding that the majority of chars will
/// fit into 8-bits and, therefore, the algorithm will retain its desirable traits
/// for generating hash codes.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The start index of the first character to hash</param>
/// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
internal static int GetFNVHashCode(string text, int start, int length)
=> GetFNVHashCode(text.AsSpan(start, length));
internal static int GetCaseInsensitiveFNVHashCode(string text)
{
return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length));
}
internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan<char> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ CaseInsensitiveComparison.ToLower(data[i])) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The start index of the first character to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns>
internal static int GetFNVHashCode(string text, int start)
{
return GetFNVHashCode(text, start, length: text.Length - start);
}
/// <summary>
/// Compute the hashcode of a string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
internal static int GetFNVHashCode(string text)
{
return CombineFNVHash(Hash.FnvOffsetBias, text);
}
/// <summary>
/// Compute the hashcode of a string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
internal static int GetFNVHashCode(System.Text.StringBuilder text)
{
int hashCode = Hash.FnvOffsetBias;
int end = text.Length;
for (int i = 0; i < end; i++)
{
hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string as a char array</param>
/// <param name="start">The start index of the first character to hash</param>
/// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
internal static int GetFNVHashCode(char[] text, int start, int length)
{
int hashCode = Hash.FnvOffsetBias;
int end = start + length;
for (int i = start; i < end; i++)
{
hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a single character using the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: In general, this isn't any more useful than "char.GetHashCode". However,
/// it may be needed if you need to generate the same hash code as a string or
/// substring with just a single character.
/// </summary>
/// <param name="ch">The character to hash</param>
/// <returns>The FNV-1a hash code of the character.</returns>
internal static int GetFNVHashCode(char ch)
{
return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch);
}
/// <summary>
/// Combine a string with an existing FNV-1a hash code
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="hashCode">The accumulated hash code</param>
/// <param name="text">The string to combine</param>
/// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns>
internal static int CombineFNVHash(int hashCode, string text)
{
foreach (char ch in text)
{
hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Combine a char with an existing FNV-1a hash code
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="hashCode">The accumulated hash code</param>
/// <param name="ch">The new character to combine</param>
/// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns>
internal static int CombineFNVHash(int hashCode, char ch)
{
return unchecked((hashCode ^ ch) * Hash.FnvPrime);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class Hash
{
/// <summary>
/// This is how VB Anonymous Types combine hash values for fields.
/// </summary>
internal static int Combine(int newKey, int currentKey)
{
return unchecked((currentKey * (int)0xA5555529) + newKey);
}
internal static int Combine(bool newKeyPart, int currentKey)
{
return Combine(currentKey, newKeyPart ? 1 : 0);
}
/// <summary>
/// This is how VB Anonymous Types combine hash values for fields.
/// PERF: Do not use with enum types because that involves multiple
/// unnecessary boxing operations. Unfortunately, we can't constrain
/// T to "non-enum", so we'll use a more restrictive constraint.
/// </summary>
internal static int Combine<T>(T newKeyPart, int currentKey) where T : class?
{
int hash = unchecked(currentKey * (int)0xA5555529);
if (newKeyPart != null)
{
return unchecked(hash + newKeyPart.GetHashCode());
}
return hash;
}
internal static int CombineValues<T>(IEnumerable<T>? values, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues<T>(T[]? values, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var maxSize = Math.Min(maxItemsToHash, values.Length);
var hashCode = 0;
for (int i = 0; i < maxSize; i++)
{
T value = values[i];
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue)
{
if (values.IsDefaultOrEmpty)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
// Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible).
if (value != null)
{
hashCode = Hash.Combine(value.GetHashCode(), hashCode);
}
}
return hashCode;
}
internal static int CombineValues(IEnumerable<string?>? values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue)
{
if (values == null)
{
return 0;
}
var hashCode = 0;
var count = 0;
foreach (var value in values)
{
if (count++ >= maxItemsToHash)
{
break;
}
if (value != null)
{
hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode);
}
}
return hashCode;
}
/// <summary>
/// The offset bias value used in the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
internal const int FnvOffsetBias = unchecked((int)2166136261);
/// <summary>
/// The generative factor used in the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
internal const int FnvPrime = 16777619;
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(byte[] data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes and determines if the byte
/// sequence is valid ASCII and hence the hash code matches a char sequence
/// encoding the same text.
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes that are likely to be ASCII text.</param>
/// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(ReadOnlySpan<byte> data, out bool isAscii)
{
int hashCode = Hash.FnvOffsetBias;
byte asciiMask = 0;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
asciiMask |= b;
hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime);
}
isAscii = (asciiMask & 0x80) == 0;
return hashCode;
}
/// <summary>
/// Compute the FNV-1a hash of a sequence of bytes
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="data">The sequence of bytes</param>
/// <returns>The FNV-1a hash of <paramref name="data"/></returns>
internal static int GetFNVHashCode(ImmutableArray<byte> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here
/// for 16-bit Unicode chars on the understanding that the majority of chars will
/// fit into 8-bits and, therefore, the algorithm will retain its desirable traits
/// for generating hash codes.
/// </summary>
internal static int GetFNVHashCode(ReadOnlySpan<char> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here
/// for 16-bit Unicode chars on the understanding that the majority of chars will
/// fit into 8-bits and, therefore, the algorithm will retain its desirable traits
/// for generating hash codes.
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The start index of the first character to hash</param>
/// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
internal static int GetFNVHashCode(string text, int start, int length)
=> GetFNVHashCode(text.AsSpan(start, length));
internal static int GetCaseInsensitiveFNVHashCode(string text)
{
return GetCaseInsensitiveFNVHashCode(text.AsSpan(0, text.Length));
}
internal static int GetCaseInsensitiveFNVHashCode(ReadOnlySpan<char> data)
{
int hashCode = Hash.FnvOffsetBias;
for (int i = 0; i < data.Length; i++)
{
hashCode = unchecked((hashCode ^ CaseInsensitiveComparison.ToLower(data[i])) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub-string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <param name="start">The start index of the first character to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns>
internal static int GetFNVHashCode(string text, int start)
{
return GetFNVHashCode(text, start, length: text.Length - start);
}
/// <summary>
/// Compute the hashcode of a string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
internal static int GetFNVHashCode(string text)
{
return CombineFNVHash(Hash.FnvOffsetBias, text);
}
/// <summary>
/// Compute the hashcode of a string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string</param>
/// <returns>The FNV-1a hash code of <paramref name="text"/></returns>
internal static int GetFNVHashCode(System.Text.StringBuilder text)
{
int hashCode = Hash.FnvOffsetBias;
int end = text.Length;
for (int i = 0; i < end; i++)
{
hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a sub string using FNV-1a
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="text">The input string as a char array</param>
/// <param name="start">The start index of the first character to hash</param>
/// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param>
/// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns>
internal static int GetFNVHashCode(char[] text, int start, int length)
{
int hashCode = Hash.FnvOffsetBias;
int end = start + length;
for (int i = start; i < end; i++)
{
hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Compute the hashcode of a single character using the FNV-1a algorithm
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// Note: In general, this isn't any more useful than "char.GetHashCode". However,
/// it may be needed if you need to generate the same hash code as a string or
/// substring with just a single character.
/// </summary>
/// <param name="ch">The character to hash</param>
/// <returns>The FNV-1a hash code of the character.</returns>
internal static int GetFNVHashCode(char ch)
{
return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch);
}
/// <summary>
/// Combine a string with an existing FNV-1a hash code
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="hashCode">The accumulated hash code</param>
/// <param name="text">The string to combine</param>
/// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns>
internal static int CombineFNVHash(int hashCode, string text)
{
foreach (char ch in text)
{
hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime);
}
return hashCode;
}
/// <summary>
/// Combine a char with an existing FNV-1a hash code
/// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// </summary>
/// <param name="hashCode">The accumulated hash code</param>
/// <param name="ch">The new character to combine</param>
/// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns>
internal static int CombineFNVHash(int hashCode, char ch)
{
return unchecked((hashCode ^ ch) * Hash.FnvPrime);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/CSharp/Portable/SignatureHelp/AbstractCSharpSignatureHelpProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal abstract class AbstractCSharpSignatureHelpProvider : AbstractSignatureHelpProvider
{
private static readonly SymbolDisplayFormat s_allowDefaultLiteralFormat = SymbolDisplayFormat.MinimallyQualifiedFormat
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
protected AbstractCSharpSignatureHelpProvider()
{
}
protected static SymbolDisplayPart Keyword(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Operator(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Operator, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Punctuation(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Text(string text)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text);
protected static SymbolDisplayPart Space()
=> new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ");
protected static SymbolDisplayPart NewLine()
=> new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
private static readonly IList<SymbolDisplayPart> _separatorParts = new List<SymbolDisplayPart>
{
Punctuation(SyntaxKind.CommaToken),
Space()
};
protected static IList<SymbolDisplayPart> GetSeparatorParts() => _separatorParts;
protected static SignatureHelpSymbolParameter Convert(
IParameterSymbol parameter,
SemanticModel semanticModel,
int position,
IDocumentationCommentFormattingService formatter)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.GetDocumentationPartsFactory(semanticModel, position, formatter),
parameter.ToMinimalDisplayParts(semanticModel, position, s_allowDefaultLiteralFormat));
}
/// <summary>
/// We no longer show awaitable usage text in SignatureHelp, but IntelliCode expects this
/// method to exist.
/// </summary>
[Obsolete("Expected to exist by IntelliCode. This can be removed once their unnecessary use of this is removed.")]
#pragma warning disable CA1822 // Mark members as static - see obsolete message above.
protected IList<TaggedText> GetAwaitableUsage(IMethodSymbol method, SemanticModel semanticModel, int position)
#pragma warning restore CA1822 // Mark members as static
=> SpecializedCollections.EmptyList<TaggedText>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
internal abstract class AbstractCSharpSignatureHelpProvider : AbstractSignatureHelpProvider
{
private static readonly SymbolDisplayFormat s_allowDefaultLiteralFormat = SymbolDisplayFormat.MinimallyQualifiedFormat
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral);
protected AbstractCSharpSignatureHelpProvider()
{
}
protected static SymbolDisplayPart Keyword(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Operator(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Operator, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Punctuation(SyntaxKind kind)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, SyntaxFacts.GetText(kind));
protected static SymbolDisplayPart Text(string text)
=> new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, text);
protected static SymbolDisplayPart Space()
=> new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ");
protected static SymbolDisplayPart NewLine()
=> new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
private static readonly IList<SymbolDisplayPart> _separatorParts = new List<SymbolDisplayPart>
{
Punctuation(SyntaxKind.CommaToken),
Space()
};
protected static IList<SymbolDisplayPart> GetSeparatorParts() => _separatorParts;
protected static SignatureHelpSymbolParameter Convert(
IParameterSymbol parameter,
SemanticModel semanticModel,
int position,
IDocumentationCommentFormattingService formatter)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.GetDocumentationPartsFactory(semanticModel, position, formatter),
parameter.ToMinimalDisplayParts(semanticModel, position, s_allowDefaultLiteralFormat));
}
/// <summary>
/// We no longer show awaitable usage text in SignatureHelp, but IntelliCode expects this
/// method to exist.
/// </summary>
[Obsolete("Expected to exist by IntelliCode. This can be removed once their unnecessary use of this is removed.")]
#pragma warning disable CA1822 // Mark members as static - see obsolete message above.
protected IList<TaggedText> GetAwaitableUsage(IMethodSymbol method, SemanticModel semanticModel, int position)
#pragma warning restore CA1822 // Mark members as static
=> SpecializedCollections.EmptyList<TaggedText>();
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/IteratorTests.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.Semantics
Public Class IteratorTests
Inherits FlowTestBase
<Fact()>
Public Sub IteratorNoYields()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
End Function
Public Iterator Function goo1 As IEnumerable
'valid
Return
End Function
Public Iterator Function goo2 As IEnumerable
'valid
Exit Function
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub BadReturnValueInIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
Return
'error
Return 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36942: To return a value from an Iterator function, use 'Yield' rather than 'Return'.
Return 123
~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub BadYieldInNonIteratorMethod()
' Cannot get the actual BadYieldInNonIteratorMethod error since Yield keyword is conditional.
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
Yield 123
End Function
Public Function goo1 As IEnumerable
'error
Yield 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30451: 'Yield' is not declared. It may be inaccessible due to its protection level.
Yield 123
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Yield 123
~~~
BC42105: Function 'goo1' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub YieldingUnassigned()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
Dim o as object
Yield o
o = 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC42104: Variable 'o' is used before it has been assigned a value. A null reference exception could result at runtime.
Yield o
~
</errors>)
End Sub
<Fact>
Public Sub YieldFlow()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Class C
Public Iterator Function goo() As IEnumerable
Dim o As Object = 1
Try
[|Yield o|]
Finally
Console.WriteLine(o)
End Try
End Function
End Class
]]></file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count())
Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count())
Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable)
Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub YieldingFromTryCatchFinally()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
Try
'valid
Yield 1
Catch ex As Exception
'error
Yield 1
Finally
'error
Yield 1
End Try
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32042: Too few type arguments to 'IEnumerable(Of Out T)'.
Public Iterator Function goo As IEnumerable
~~~~~~~~~~~
BC36939: 'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.
Yield 1
~~~~~~~
BC36939: 'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.
Yield 1
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub NoConversion()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Exception)
Yield 1
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30311: Value of type 'Integer' cannot be converted to 'Exception'.
Yield 1
~
</errors>)
End Sub
<Fact()>
Public Sub NotReadable()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Exception)
Yield P1
End Function
WriteOnly Property P1 As Exception
Set(value As Exception)
End Set
End Property
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30524: Property 'P1' is 'WriteOnly'.
Yield P1
~~
</errors>)
End Sub
<Fact()>
Public Sub LambdaConversions()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Func(of Integer, Integer))
Yield Function() New Long
End Function
Public Iterator Function goo1 As IEnumerable(of Func(of String, Short, Integer))
Yield Function(x, y) x.length + y
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub InvalidParamType()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function f2(ByVal a As ArgIterator) As IEnumerator
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Public Iterator Function f2(ByVal a As ArgIterator) As IEnumerator
~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub EnumeratorNotImported()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function f1(o As Object) As IEnumerable
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32042: Too few type arguments to 'IEnumerable(Of Out T)'.
Public Iterator Function f1(o As Object) As IEnumerable
~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub ByRefParams()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function f1(ByRef o As Object) As IEnumerable
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36927: Iterator methods cannot have ByRef parameters.
Public Iterator Function f1(ByRef o As Object) As IEnumerable
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub IteratorTypeWrong()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
Dim i = Iterator Function() As object
yield 123
End Function
End Sub
Public Iterator Function f1( o As Object) As Object
yield 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i = Iterator Function() As object
~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public Iterator Function f1( o As Object) As Object
~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub SubIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
Dim i = Iterator Sub()
yield 123
End Sub
Dim i1 = Iterator Sub() yield 123
End Sub
Public Iterator Sub f1( o As Object)
yield 123
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i = Iterator Sub()
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i1 = Iterator Sub() yield 123
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public Iterator Sub f1( o As Object)
~~~
</errors>)
End Sub
<Fact()>
Public Sub StaticInIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Iterator Function t4() As System.Collections.IEnumerator
Static x As Integer = 1
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static x As Integer = 1
~
</errors>)
End Sub
<Fact()>
Public Sub MiscInvalid()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
End Sub
<DllImport("user32.dll")> Iterator Function f3() As System.Collections.IEnumerator
End Function
' Synchronized seems to be Ok
<MethodImpl(MethodImplOptions.Synchronized)>
Iterator Function f6() As System.Collections.IEnumerator
End Function
Declare iterator function f5 Lib "user32.dll" () as integer
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
<DllImport("user32.dll")> Iterator Function f3() As System.Collections.IEnumerator
~~
BC30215: 'Sub' or 'Function' expected.
Declare iterator function f5 Lib "user32.dll" () as integer
~
BC30218: 'Lib' expected.
Declare iterator function f5 Lib "user32.dll" () as integer
~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub IteratorInWrongPlaces()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x = {Iterator sub() yield, new object}
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
Dim z = {Sub() AddHandler, New Object}
g0(Iterator sub() Yield)
g1(Iterator Sub() Yield, 5)
End Sub
Sub g0(ByVal x As Func(Of IEnumerator))
End Sub
Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer)
End Sub
Iterator Function f() As IEnumerator
Yield
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim x = {Iterator sub() yield, new object}
~~~
BC30201: Expression expected.
Dim x = {Iterator sub() yield, new object}
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~~~
BC30201: Expression expected.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~
BC30201: Expression expected.
Dim z = {Sub() AddHandler, New Object}
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
g0(Iterator sub() Yield)
~~~
BC30201: Expression expected.
g0(Iterator sub() Yield)
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
g1(Iterator Sub() Yield, 5)
~~~
BC30201: Expression expected.
g1(Iterator Sub() Yield, 5)
~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Sub g0(ByVal x As Func(Of IEnumerator))
~~~~~~~~~~~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer)
~~~~~~~~~~~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Iterator Function f() As IEnumerator
~~~~~~~~~~~
BC30201: Expression expected.
Yield
~
</errors>)
End Sub
<Fact()>
Public Sub InferenceByrefLike()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim i = Iterator Function()
yield New ArgIterator
End Function
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim i = Iterator Function()
~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceByref()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public sub rr(byref x as Integer)
Dim i = Iterator Function()
Yield x
End Function
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
Yield x
~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
' not an error
Dim o As Object = Iterator Function()
Yield 1
End Function
Dim i As Func(Of String) = Iterator Function()
Yield 1
End Function
goo(i)
bar(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub goo(Of T)(x As Func(Of T))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
Public Sub bar(x As Func(Of String))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i As Func(Of String) = Iterator Function()
~~~~~~~~~~~~~~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
bar(Iterator Function()
~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
baz(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub baz(Of T)(x As Func(Of IEnumerator(Of T)))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub baz(Of T)(x As Func(Of IEnumerator(Of T)))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
baz(Iterator Function()
~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
baz(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub baz(Of T)(x As Func(Of IEnumerable(Of T)))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>)
End Sub
<Fact(), WorkItem(629565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629565")>
Public Sub Bug629565()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module ModuleChanges2
Sub Goo(x1 As Func(Of IEnumerable(Of Object)))
System.Console.WriteLine("Object")
End Sub
Sub Goo(x2 As Func(Of IEnumerable(Of Integer)))
System.Console.WriteLine("Integer")
End Sub
Sub Bar(x1 As Func(Of IEnumerable(Of Object)))
System.Console.WriteLine("Object")
End Sub
End Module
Module Program
Sub Main()
Goo(Iterator Function()
Yield 2.0
End Function)
Bar(Iterator Function()
Yield 2.0
End Function)
End Sub
End Module
]]>
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation,
<![CDATA[
Object
Object
]]>)
End Sub
<Fact(), WorkItem(1006315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1006315")>
Public Sub BadAsyncSingleLineLambda()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Function E() As IEnumerable(Of Integer)
Return Nothing
End Function
Sub Main(args As String())
Dim x As Func(Of IEnumerable(Of Integer)) = Iterator Function() E()
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36947: Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.
Dim x As Func(Of IEnumerable(Of Integer)) = Iterator Function() E()
~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact(), WorkItem(1173145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1173145"), WorkItem(2862, "https://github.com/dotnet/roslyn/issues/2862")>
Public Sub CompoundAssignmentToAField()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Collections
Imports System.Collections.Generic
Module Module1
Sub Main()
For Each x In New MyEnumerable(Of Integer)({100, 99, 98})
System.Console.WriteLine(x)
Next
End Sub
End Module
Public Class MyEnumerable(Of T)
Implements IEnumerable(Of T)
Private ReadOnly _items As T()
Private _count As Integer = 0
Public Sub New(items As T())
_items = items
_count = items.Length
End Sub
Public Iterator Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
For Each item In _items
If _count = 0 Then Exit Function
_count -= 1
Yield item
Next
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
End Class
]]>
</file>
</compilation>, TestOptions.DebugExe)
Dim expected As Xml.Linq.XCData = <![CDATA[
100
99
98
]]>
CompileAndVerify(compilation, expected)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expected)
End Sub
<Fact>
<WorkItem(11531, "https://github.com/dotnet/roslyn/issues/11531")>
<WorkItem(220696, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=220696")>
Public Sub WritableIteratorProperty()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
MustInherit Class A
MustOverride Iterator Property P As IEnumerable(Of Object)
End Class
Class B
Private _p As IEnumerable(Of Object)
Iterator Property P As IEnumerable(Of Object)
Get
For Each o in _p
Yield o
Next
End Get
Set
_p = value
End Set
End Property
Shared Sub Main()
Dim b As New B()
b.P = {1, 2, 3}
For Each o in b.P
Console.Write(o)
Next
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugExe) ' generate debug info
compilation.AssertTheseEmitDiagnostics(<expected/>)
Dim [property] = compilation.GetMember(Of PropertySymbol)("A.P")
Assert.True([property].GetMethod.IsIterator)
Assert.False([property].SetMethod.IsIterator)
[property] = compilation.GetMember(Of PropertySymbol)("B.P")
Assert.True([property].GetMethod.IsIterator)
Assert.False([property].SetMethod.IsIterator)
CompileAndVerify(compilation, expectedOutput:="123")
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.Semantics
Public Class IteratorTests
Inherits FlowTestBase
<Fact()>
Public Sub IteratorNoYields()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
End Function
Public Iterator Function goo1 As IEnumerable
'valid
Return
End Function
Public Iterator Function goo2 As IEnumerable
'valid
Exit Function
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub BadReturnValueInIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
Return
'error
Return 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36942: To return a value from an Iterator function, use 'Yield' rather than 'Return'.
Return 123
~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub BadYieldInNonIteratorMethod()
' Cannot get the actual BadYieldInNonIteratorMethod error since Yield keyword is conditional.
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
'valid
Yield 123
End Function
Public Function goo1 As IEnumerable
'error
Yield 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30451: 'Yield' is not declared. It may be inaccessible due to its protection level.
Yield 123
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Yield 123
~~~
BC42105: Function 'goo1' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub YieldingUnassigned()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
Dim o as object
Yield o
o = 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC42104: Variable 'o' is used before it has been assigned a value. A null reference exception could result at runtime.
Yield o
~
</errors>)
End Sub
<Fact>
Public Sub YieldFlow()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Class C
Public Iterator Function goo() As IEnumerable
Dim o As Object = 1
Try
[|Yield o|]
Finally
Console.WriteLine(o)
End Try
End Function
End Class
]]></file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count())
Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count())
Assert.Equal(True, controlFlowAnalysisResults.StartPointIsReachable)
Assert.Equal(True, controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, o", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub YieldingFromTryCatchFinally()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable
Try
'valid
Yield 1
Catch ex As Exception
'error
Yield 1
Finally
'error
Yield 1
End Try
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32042: Too few type arguments to 'IEnumerable(Of Out T)'.
Public Iterator Function goo As IEnumerable
~~~~~~~~~~~
BC36939: 'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.
Yield 1
~~~~~~~
BC36939: 'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.
Yield 1
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub NoConversion()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Exception)
Yield 1
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30311: Value of type 'Integer' cannot be converted to 'Exception'.
Yield 1
~
</errors>)
End Sub
<Fact()>
Public Sub NotReadable()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Exception)
Yield P1
End Function
WriteOnly Property P1 As Exception
Set(value As Exception)
End Set
End Property
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30524: Property 'P1' is 'WriteOnly'.
Yield P1
~~
</errors>)
End Sub
<Fact()>
Public Sub LambdaConversions()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function goo As IEnumerable(of Func(of Integer, Integer))
Yield Function() New Long
End Function
Public Iterator Function goo1 As IEnumerable(of Func(of String, Short, Integer))
Yield Function(x, y) x.length + y
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub InvalidParamType()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function f2(ByVal a As ArgIterator) As IEnumerator
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Public Iterator Function f2(ByVal a As ArgIterator) As IEnumerator
~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub EnumeratorNotImported()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public Iterator Function f1(o As Object) As IEnumerable
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC32042: Too few type arguments to 'IEnumerable(Of Out T)'.
Public Iterator Function f1(o As Object) As IEnumerable
~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub ByRefParams()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
End Sub
Public Iterator Function f1(ByRef o As Object) As IEnumerable
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36927: Iterator methods cannot have ByRef parameters.
Public Iterator Function f1(ByRef o As Object) As IEnumerable
~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub IteratorTypeWrong()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
Dim i = Iterator Function() As object
yield 123
End Function
End Sub
Public Iterator Function f1( o As Object) As Object
yield 123
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i = Iterator Function() As object
~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public Iterator Function f1( o As Object) As Object
~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub SubIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Module Module1
Sub Main()
Dim i = Iterator Sub()
yield 123
End Sub
Dim i1 = Iterator Sub() yield 123
End Sub
Public Iterator Sub f1( o As Object)
yield 123
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i = Iterator Sub()
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i1 = Iterator Sub() yield 123
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public Iterator Sub f1( o As Object)
~~~
</errors>)
End Sub
<Fact()>
Public Sub StaticInIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Iterator Function t4() As System.Collections.IEnumerator
Static x As Integer = 1
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static x As Integer = 1
~
</errors>)
End Sub
<Fact()>
Public Sub MiscInvalid()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
End Sub
<DllImport("user32.dll")> Iterator Function f3() As System.Collections.IEnumerator
End Function
' Synchronized seems to be Ok
<MethodImpl(MethodImplOptions.Synchronized)>
Iterator Function f6() As System.Collections.IEnumerator
End Function
Declare iterator function f5 Lib "user32.dll" () as integer
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
<DllImport("user32.dll")> Iterator Function f3() As System.Collections.IEnumerator
~~
BC30215: 'Sub' or 'Function' expected.
Declare iterator function f5 Lib "user32.dll" () as integer
~
BC30218: 'Lib' expected.
Declare iterator function f5 Lib "user32.dll" () as integer
~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub IteratorInWrongPlaces()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x = {Iterator sub() yield, new object}
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
Dim z = {Sub() AddHandler, New Object}
g0(Iterator sub() Yield)
g1(Iterator Sub() Yield, 5)
End Sub
Sub g0(ByVal x As Func(Of IEnumerator))
End Sub
Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer)
End Sub
Iterator Function f() As IEnumerator
Yield
End Function
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim x = {Iterator sub() yield, new object}
~~~
BC30201: Expression expected.
Dim x = {Iterator sub() yield, new object}
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~~~
BC30201: Expression expected.
Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object}
~
BC30201: Expression expected.
Dim z = {Sub() AddHandler, New Object}
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
g0(Iterator sub() Yield)
~~~
BC30201: Expression expected.
g0(Iterator sub() Yield)
~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
g1(Iterator Sub() Yield, 5)
~~~
BC30201: Expression expected.
g1(Iterator Sub() Yield, 5)
~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Sub g0(ByVal x As Func(Of IEnumerator))
~~~~~~~~~~~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer)
~~~~~~~~~~~
BC32042: Too few type arguments to 'IEnumerator(Of Out T)'.
Iterator Function f() As IEnumerator
~~~~~~~~~~~
BC30201: Expression expected.
Yield
~
</errors>)
End Sub
<Fact()>
Public Sub InferenceByrefLike()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim i = Iterator Function()
yield New ArgIterator
End Function
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim i = Iterator Function()
~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceByref()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
End Sub
Public sub rr(byref x as Integer)
Dim i = Iterator Function()
Yield x
End Function
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
Yield x
~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
' not an error
Dim o As Object = Iterator Function()
Yield 1
End Function
Dim i As Func(Of String) = Iterator Function()
Yield 1
End Function
goo(i)
bar(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub goo(Of T)(x As Func(Of T))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
Public Sub bar(x As Func(Of String))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Dim i As Func(Of String) = Iterator Function()
~~~~~~~~~~~~~~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
bar(Iterator Function()
~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
baz(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub baz(Of T)(x As Func(Of IEnumerator(Of T)))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub baz(Of T)(x As Func(Of IEnumerator(Of T)))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
baz(Iterator Function()
~~~
</errors>)
End Sub
<Fact()>
Public Sub InferenceErrors_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
baz(Iterator Function()
Yield 1
End Function)
End Sub
Public Sub baz(Of T)(x As Func(Of IEnumerable(Of T)))
Console.WriteLine(GetType(T))
Console.WriteLine(x.GetType())
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>)
End Sub
<Fact(), WorkItem(629565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629565")>
Public Sub Bug629565()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Option Strict Off
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module ModuleChanges2
Sub Goo(x1 As Func(Of IEnumerable(Of Object)))
System.Console.WriteLine("Object")
End Sub
Sub Goo(x2 As Func(Of IEnumerable(Of Integer)))
System.Console.WriteLine("Integer")
End Sub
Sub Bar(x1 As Func(Of IEnumerable(Of Object)))
System.Console.WriteLine("Object")
End Sub
End Module
Module Program
Sub Main()
Goo(Iterator Function()
Yield 2.0
End Function)
Bar(Iterator Function()
Yield 2.0
End Function)
End Sub
End Module
]]>
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation,
<![CDATA[
Object
Object
]]>)
End Sub
<Fact(), WorkItem(1006315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1006315")>
Public Sub BadAsyncSingleLineLambda()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Function E() As IEnumerable(Of Integer)
Return Nothing
End Function
Sub Main(args As String())
Dim x As Func(Of IEnumerable(Of Integer)) = Iterator Function() E()
End Sub
End Module
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC36947: Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.
Dim x As Func(Of IEnumerable(Of Integer)) = Iterator Function() E()
~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact(), WorkItem(1173145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1173145"), WorkItem(2862, "https://github.com/dotnet/roslyn/issues/2862")>
Public Sub CompoundAssignmentToAField()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Collections
Imports System.Collections.Generic
Module Module1
Sub Main()
For Each x In New MyEnumerable(Of Integer)({100, 99, 98})
System.Console.WriteLine(x)
Next
End Sub
End Module
Public Class MyEnumerable(Of T)
Implements IEnumerable(Of T)
Private ReadOnly _items As T()
Private _count As Integer = 0
Public Sub New(items As T())
_items = items
_count = items.Length
End Sub
Public Iterator Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
For Each item In _items
If _count = 0 Then Exit Function
_count -= 1
Yield item
Next
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
End Class
]]>
</file>
</compilation>, TestOptions.DebugExe)
Dim expected As Xml.Linq.XCData = <![CDATA[
100
99
98
]]>
CompileAndVerify(compilation, expected)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expected)
End Sub
<Fact>
<WorkItem(11531, "https://github.com/dotnet/roslyn/issues/11531")>
<WorkItem(220696, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=220696")>
Public Sub WritableIteratorProperty()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
MustInherit Class A
MustOverride Iterator Property P As IEnumerable(Of Object)
End Class
Class B
Private _p As IEnumerable(Of Object)
Iterator Property P As IEnumerable(Of Object)
Get
For Each o in _p
Yield o
Next
End Get
Set
_p = value
End Set
End Property
Shared Sub Main()
Dim b As New B()
b.P = {1, 2, 3}
For Each o in b.P
Console.Write(o)
Next
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugExe) ' generate debug info
compilation.AssertTheseEmitDiagnostics(<expected/>)
Dim [property] = compilation.GetMember(Of PropertySymbol)("A.P")
Assert.True([property].GetMethod.IsIterator)
Assert.False([property].SetMethod.IsIterator)
[property] = compilation.GetMember(Of PropertySymbol)("B.P")
Assert.True([property].GetMethod.IsIterator)
Assert.False([property].SetMethod.IsIterator)
CompileAndVerify(compilation, expectedOutput:="123")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId,
EnforceOnBuildValues.UseNullCheckOverTypeCheck,
CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(context =>
{
if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9)
{
return;
}
context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType);
context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern);
});
}
private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity)
{
var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken);
if (!option.Value)
{
severity = ReportDiagnostic.Default;
return false;
}
severity = option.Notification.Severity;
return true;
}
private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not UnaryPatternSyntax)
{
return;
}
var negatedPattern = (INegatedPatternOperation)context.Operation;
// Matches 'x is not MyType'
// InputType is the type of 'x'
// MatchedType is 'MyType'
// We check InheritsFromOrEquals so that we report a diagnostic on the following:
// 1. x is not object (which is also equivalent to 'is null' check)
// 2. derivedObj is parentObj (which is the same as the previous point).
// 3. str is string (where str is a string, this is also equivalent to 'is null' check).
// This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will
// be `DeclarationPattern`, not `TypePattern`.
if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation &&
typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType))
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null));
}
}
private void AnalyzeIsTypeOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not BinaryExpressionSyntax)
{
return;
}
var isTypeOperation = (IIsTypeOperation)context.Operation;
// Matches 'x is MyType'
// isTypeOperation.TypeOperand is 'MyType'
// isTypeOperation.ValueOperand.Type is the type of 'x'.
// We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation.
// This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation.
if (isTypeOperation.ValueOperand.Type is not null &&
isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand))
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: 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 Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId,
EnforceOnBuildValues.UseNullCheckOverTypeCheck,
CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(context =>
{
if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9)
{
return;
}
context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType);
context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern);
});
}
private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity)
{
var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken);
if (!option.Value)
{
severity = ReportDiagnostic.Default;
return false;
}
severity = option.Notification.Severity;
return true;
}
private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not UnaryPatternSyntax)
{
return;
}
var negatedPattern = (INegatedPatternOperation)context.Operation;
// Matches 'x is not MyType'
// InputType is the type of 'x'
// MatchedType is 'MyType'
// We check InheritsFromOrEquals so that we report a diagnostic on the following:
// 1. x is not object (which is also equivalent to 'is null' check)
// 2. derivedObj is parentObj (which is the same as the previous point).
// 3. str is string (where str is a string, this is also equivalent to 'is null' check).
// This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will
// be `DeclarationPattern`, not `TypePattern`.
if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation &&
typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType))
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null));
}
}
private void AnalyzeIsTypeOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not BinaryExpressionSyntax)
{
return;
}
var isTypeOperation = (IIsTypeOperation)context.Operation;
// Matches 'x is MyType'
// isTypeOperation.TypeOperand is 'MyType'
// isTypeOperation.ValueOperand.Type is the type of 'x'.
// We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation.
// This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation.
if (isTypeOperation.ValueOperand.Type is not null &&
isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand))
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null));
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/DataFlowPass.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.PooledObjects
#If DEBUG Then
' We use a struct rather than a class to represent the state for efficiency
' for data flow analysis, with 32 bits of data inline. Merely copying the state
' variable causes the first 32 bits to be cloned, as they are inline. This can
' hide a plethora of errors that would only be exhibited in programs with more
' than 32 variables to be tracked. However, few of our tests have that many
' variables.
'
' To help diagnose these problems, we use the preprocessor symbol REFERENCE_STATE
' to cause the data flow state be a class rather than a struct. When it is a class,
' this category of problems would be exhibited in programs with a small number of
' tracked variables. But it is slower, so we only do it in DEBUG mode.
#Const REFERENCE_STATE = True
#End If
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
#If REFERENCE_STATE Then
Imports OptionalState = Microsoft.CodeAnalysis.[Optional](Of Microsoft.CodeAnalysis.VisualBasic.DataFlowPass.LocalState)
#Else
Imports OptionalState = System.Nullable(Of Microsoft.CodeAnalysis.VisualBasic.DataFlowPass.LocalState)
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class DataFlowPass
Inherits AbstractFlowPass(Of LocalState)
Public Enum SlotKind
''' <summary>
''' Special slot for untracked variables
''' </summary>
NotTracked = -1
''' <summary>
''' Special slot for tracking whether code is reachable
''' </summary>
Unreachable = 0
''' <summary>
''' Special slot for tracking the implicit local for the function return value
''' </summary>
FunctionValue = 1
''' <summary>
''' The first available slot for variables
''' </summary>
''' <remarks></remarks>
FirstAvailable = 2
End Enum
''' <summary>
''' Some variables that should be considered initially assigned. Used for region analysis.
''' </summary>
Protected ReadOnly initiallyAssignedVariables As HashSet(Of Symbol)
''' <summary>
''' Defines whether or not fields of intrinsic type should be tracked. Such fields should
''' not be tracked for error reporting purposes, but should be tracked for region flow analysis
''' </summary>
Private ReadOnly _trackStructsWithIntrinsicTypedFields As Boolean
''' <summary>
''' Variables that were used anywhere, in the sense required to suppress warnings about unused variables.
''' </summary>
Private ReadOnly _unusedVariables As HashSet(Of LocalSymbol) = New HashSet(Of LocalSymbol)()
''' <summary>
''' Variables that were initialized or written anywhere.
''' </summary>
Private ReadOnly _writtenVariables As HashSet(Of Symbol) = New HashSet(Of Symbol)()
''' <summary>
''' A mapping from local variables to the index of their slot in a flow analysis local state.
''' WARNING: if variable identifier maps into SlotKind.NotTracked, it may mean that VariableIdentifier
''' is a structure without traceable fields. This mapping is created in MakeSlotImpl(...)
''' </summary>
Private ReadOnly _variableSlot As Dictionary(Of VariableIdentifier, Integer) = New Dictionary(Of VariableIdentifier, Integer)()
''' <summary>
''' A mapping from the local variable slot to the symbol for the local variable itself. This is used in the
''' implementation of region analysis (support for extract method) to compute the set of variables "always
''' assigned" in a region of code.
''' </summary>
Protected variableBySlot As VariableIdentifier() = New VariableIdentifier(10) {}
''' <summary>
''' Variable slots are allocated to local variables sequentially and never reused. This is
''' the index of the next slot number to use.
''' </summary>
Protected nextVariableSlot As Integer = SlotKind.FirstAvailable
''' <summary>
''' Tracks variables for which we have already reported a definite assignment error. This
''' allows us to report at most one such error per variable.
''' </summary>
Private _alreadyReported As BitVector
''' <summary>
''' Did we see [On Error] or [Resume] statement? Used to suppress some diagnostics.
''' </summary>
Private _seenOnErrorOrResume As Boolean
Protected _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException As Boolean = False ' By default, just let the original exception to bubble up.
Friend Sub New(info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean, Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, suppressConstExpressionsSupport)
Me.initiallyAssignedVariables = Nothing
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo,
suppressConstExpressionsSupport As Boolean,
Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing,
Optional trackUnassignments As Boolean = False,
Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, region, suppressConstExpressionsSupport, trackUnassignments)
Me.initiallyAssignedVariables = initiallyAssignedVariables
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Protected Overrides Sub InitForScan()
MyBase.InitForScan()
For Each parameter In MethodParameters
GetOrCreateSlot(parameter)
Next
Me._alreadyReported = BitVector.Empty ' no variables yet reported unassigned
Me.EnterParameters(MethodParameters) ' with parameters assigned
Dim methodMeParameter = Me.MeParameter ' and with 'Me' assigned as well
If methodMeParameter IsNot Nothing Then
Me.GetOrCreateSlot(methodMeParameter)
Me.EnterParameter(methodMeParameter)
End If
' Usually we need to treat locals used without being assigned first as assigned in the beginning of the block.
' When data flow analysis determines that the variable is sometimes used without being assigned first, we want
' to treat that variable, during region analysis, as assigned where it is introduced.
' However with goto statements that branch into for/foreach/using statements (error case) we need to treat them
' as assigned in the beginning of the method body.
'
' Example:
' Goto label1
' For x = 0 to 10
' label1:
' Dim y = [| x |] ' x should not be in dataFlowsOut.
' Next
'
' This can only happen in VB because the labels are visible in the whole method. In C# the labels are not visible
' this case.
'
If initiallyAssignedVariables IsNot Nothing Then
For Each local In initiallyAssignedVariables
SetSlotAssigned(GetOrCreateSlot(local))
Next
End If
End Sub
Protected Overrides Function Scan() As Boolean
If Not MyBase.Scan() Then
Return False
End If
' check unused variables
If Not _seenOnErrorOrResume Then
For Each local In _unusedVariables
ReportUnused(local)
Next
End If
' VB doesn't support "out" so it doesn't warn for unassigned parameters. However, check variables passed
' byref are assigned so that data flow analysis detects parameters flowing out.
If ShouldAnalyzeByRefParameters Then
LeaveParameters(MethodParameters)
End If
Dim methodMeParameter = Me.MeParameter ' and also 'Me'
If methodMeParameter IsNot Nothing Then
Me.LeaveParameter(methodMeParameter)
End If
Return True
End Function
Private Sub ReportUnused(local As LocalSymbol)
' Never report that the function value is unused
' Never report that local with empty name is unused
' Locals with empty name can be generated in code with syntax errors and
' we shouldn't report such locals as unused because they were not explicitly declared
' by the user in the code
If Not local.IsFunctionValue AndAlso Not String.IsNullOrEmpty(local.Name) Then
If _writtenVariables.Contains(local) Then
If local.IsConst Then
Me.diagnostics.Add(ERRID.WRN_UnusedLocalConst, local.Locations(0), If(local.Name, "dummy"))
End If
Else
Me.diagnostics.Add(ERRID.WRN_UnusedLocal, local.Locations(0), If(local.Name, "dummy"))
End If
End If
End Sub
Protected Overridable Sub ReportUnassignedByRefParameter(parameter As ParameterSymbol)
End Sub
''' <summary>
''' Perform data flow analysis, reporting all necessary diagnostics.
''' </summary>
Public Overloads Shared Sub Analyze(info As FlowAnalysisInfo, diagnostics As DiagnosticBag, suppressConstExpressionsSupport As Boolean)
Dim walker = New DataFlowPass(info, suppressConstExpressionsSupport)
If diagnostics IsNot Nothing Then
walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = True
End If
Try
Dim result As Boolean = walker.Analyze()
Debug.Assert(result)
If diagnostics IsNot Nothing Then
diagnostics.AddRange(walker.diagnostics)
End If
Catch ex As CancelledByStackGuardException When diagnostics IsNot Nothing
ex.AddAnError(diagnostics)
Finally
walker.Free()
End Try
End Sub
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
Return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException
End Function
Protected Overrides Sub Free()
Me._alreadyReported = BitVector.Null
MyBase.Free()
End Sub
Protected Overrides Function Dump(state As LocalState) As String
Dim builder As New StringBuilder()
builder.Append("[assigned ")
AppendBitNames(state.Assigned, builder)
builder.Append("]")
Return builder.ToString()
End Function
Protected Sub AppendBitNames(a As BitVector, builder As StringBuilder)
Dim any As Boolean = False
For Each bit In a.TrueBits
If any Then
builder.Append(", ")
End If
any = True
AppendBitName(bit, builder)
Next
End Sub
Protected Sub AppendBitName(bit As Integer, builder As StringBuilder)
Dim id As VariableIdentifier = variableBySlot(bit)
If id.ContainingSlot > 0 Then
AppendBitName(id.ContainingSlot, builder)
builder.Append(".")
End If
builder.Append(If(bit = 0, "*", id.Symbol.Name))
End Sub
#Region "Note Read/Write"
Protected Overridable Sub NoteRead(variable As Symbol)
If variable IsNot Nothing AndAlso variable.Kind = SymbolKind.Local Then
_unusedVariables.Remove(DirectCast(variable, LocalSymbol))
End If
End Sub
Protected Overridable Sub NoteWrite(variable As Symbol, value As BoundExpression)
If variable IsNot Nothing Then
_writtenVariables.Add(variable)
Dim local = TryCast(variable, LocalSymbol)
If value IsNot Nothing AndAlso (local IsNot Nothing AndAlso Not local.IsConst AndAlso local.Type.IsReferenceType OrElse value.HasErrors) Then
' We duplicate Dev10's behavior here. The reasoning is, I would guess, that otherwise unread
' variables of reference type are useful because they keep objects alive, i.e., they are read by the
' VM. And variables that are initialized by non-constant expressions presumably are useful because
' they enable us to clearly document a discarded return value from a method invocation, e.g. var
' discardedValue = F(); >shrug<
' Note, this rule only applies to local variables and not to const locals, i.e. we always report unused
' const locals. In addition, if the value has errors then suppress these diagnostics in all cases.
_unusedVariables.Remove(local)
End If
End If
End Sub
Protected Function GetNodeSymbol(node As BoundNode) As Symbol
While node IsNot Nothing
Select Case node.Kind
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If FieldAccessMayRequireTracking(fieldAccess) Then
node = fieldAccess.ReceiverOpt
Continue While
End If
Return Nothing
Case BoundKind.PropertyAccess
node = DirectCast(node, BoundPropertyAccess).ReceiverOpt
Continue While
Case BoundKind.MeReference
Return MeParameter
Case BoundKind.Local
Return DirectCast(node, BoundLocal).LocalSymbol
Case BoundKind.RangeVariable
Return DirectCast(node, BoundRangeVariable).RangeVariable
Case BoundKind.Parameter
Return DirectCast(node, BoundParameter).ParameterSymbol
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return GetNodeSymbol(substitute)
End If
Return Nothing
Case BoundKind.LocalDeclaration
Return DirectCast(node, BoundLocalDeclaration).LocalSymbol
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Return DirectCast(node, BoundForStatement).DeclaredOrInferredLocalOpt
Case BoundKind.ByRefArgumentWithCopyBack
node = DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument
Continue While
Case Else
Return Nothing
End Select
End While
Return Nothing
End Function
Protected Overridable Sub NoteWrite(node As BoundExpression, value As BoundExpression)
Dim symbol As Symbol = GetNodeSymbol(node)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteWrite(local, value)
Next
Else
NoteWrite(symbol, value)
End If
End If
End Sub
Protected Overridable Sub NoteRead(fieldAccess As BoundFieldAccess)
Dim symbol As Symbol = GetNodeSymbol(fieldAccess)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteRead(local)
Next
Else
NoteRead(symbol)
End If
End If
End Sub
#End Region
#Region "Operations with slots"
''' <summary>
''' Locals are given slots when their declarations are encountered. We only need give slots to local variables, and
''' the "Me" variable of a structure constructs. Other variables are not given slots, and are therefore not tracked
''' by the analysis. This returns SlotKind.NotTracked for a variable that is not tracked, for fields of structs
''' that have the same assigned status as the container, and for structs that (recursively) contain no data members.
''' We do not need to track references to variables that occur before the variable is declared, as those are reported
''' in an earlier phase as "use before declaration". That allows us to avoid giving slots to local variables before
''' processing their declarations.
''' </summary>
Protected Function VariableSlot(symbol As Symbol, Optional containingSlot As Integer = 0) As Integer
containingSlot = DescendThroughTupleRestFields(symbol, containingSlot, forceContainingSlotsToExist:=False)
If symbol Is Nothing Then
' NOTE: This point may be hit in erroneous code, like
' referencing instance members from static methods
Return SlotKind.NotTracked
End If
Dim slot As Integer
Return If((_variableSlot.TryGetValue(New VariableIdentifier(symbol, containingSlot), slot)), slot, SlotKind.NotTracked)
End Function
''' <summary>
''' Return the slot for a variable, or SlotKind.NotTracked if it is not tracked (because, for example, it is an empty struct).
''' </summary>
Protected Function MakeSlotsForExpression(node As BoundExpression) As SlotCollection
Dim result As New SlotCollection() ' empty
Select Case node.Kind
Case BoundKind.MeReference, BoundKind.MyBaseReference, BoundKind.MyClassReference
If MeParameter IsNot Nothing Then
result.Append(GetOrCreateSlot(MeParameter))
End If
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' multiple locals
For Each loc In DirectCast(local, AmbiguousLocalsPseudoSymbol).Locals
result.Append(GetOrCreateSlot(loc))
Next
Else
' just one simple local
result.Append(GetOrCreateSlot(local))
End If
Case BoundKind.RangeVariable
result.Append(GetOrCreateSlot(DirectCast(node, BoundRangeVariable).RangeVariable))
Case BoundKind.Parameter
result.Append(GetOrCreateSlot(DirectCast(node, BoundParameter).ParameterSymbol))
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
Dim fieldsymbol = fieldAccess.FieldSymbol
Dim receiverOpt = fieldAccess.ReceiverOpt
' do not track static fields
If fieldsymbol.IsShared OrElse receiverOpt Is Nothing OrElse receiverOpt.Kind = BoundKind.TypeExpression Then
Exit Select ' empty result
End If
' do not track fields of non-structs
If receiverOpt.Type Is Nothing OrElse receiverOpt.Type.TypeKind <> TypeKind.Structure Then
Exit Select ' empty result
End If
result = MakeSlotsForExpression(receiverOpt)
' update slots, reuse collection
' NOTE: we don't filter out SlotKind.NotTracked values
For i = 0 To result.Count - 1
result(i) = GetOrCreateSlot(fieldAccess.FieldSymbol, result(0))
Next
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return MakeSlotsForExpression(substitute)
End If
End Select
Return result
End Function
''' <summary>
''' Force a variable to have a slot.
''' </summary>
''' <param name = "symbol"></param>
''' <returns></returns>
Protected Function GetOrCreateSlot(symbol As Symbol, Optional containingSlot As Integer = 0) As Integer
containingSlot = DescendThroughTupleRestFields(symbol, containingSlot, forceContainingSlotsToExist:=True)
If containingSlot = SlotKind.NotTracked Then
Return SlotKind.NotTracked
End If
' Check if the slot already exists
Dim varIdentifier As New VariableIdentifier(symbol, containingSlot)
Dim slot As Integer
If Not _variableSlot.TryGetValue(varIdentifier, slot) Then
If symbol.Kind = SymbolKind.Local Then
Me._unusedVariables.Add(DirectCast(symbol, LocalSymbol))
End If
Dim variableType As TypeSymbol = GetVariableType(symbol)
If IsEmptyStructType(variableType) Then
Return SlotKind.NotTracked
End If
' Create a slot
slot = nextVariableSlot
nextVariableSlot = nextVariableSlot + 1
_variableSlot.Add(varIdentifier, slot)
If slot >= variableBySlot.Length Then
Array.Resize(Me.variableBySlot, slot * 2)
End If
variableBySlot(slot) = varIdentifier
End If
Me.Normalize(Me.State)
Return slot
End Function
''' <summary>
''' Descends through Rest fields of a tuple if "symbol" is an extended field
''' As a result the "symbol" will be adjusted to be the field of the innermost tuple
''' and a corresponding containingSlot is returned.
''' Return value -1 indicates a failure which could happen for the following reasons
''' a) Rest field does not exist, which could happen in rare error scenarios involving broken ValueTuple types
''' b) Rest is not tracked already and forceSlotsToExist is false (otherwise we create slots on demand)
''' </summary>
Private Function DescendThroughTupleRestFields(ByRef symbol As Symbol, containingSlot As Integer, forceContainingSlotsToExist As Boolean) As Integer
Dim fieldSymbol = TryCast(symbol, TupleFieldSymbol)
If fieldSymbol IsNot Nothing Then
Dim containingType As TypeSymbol = DirectCast(symbol.ContainingType, TupleTypeSymbol).UnderlyingNamedType
' for tuple fields the variable identifier represents the underlying field
symbol = fieldSymbol.TupleUnderlyingField
' descend through Rest fields
' force corresponding slots if do not exist
While Not TypeSymbol.Equals(containingType, symbol.ContainingType, TypeCompareKind.ConsiderEverything)
Dim restField = TryCast(containingType.GetMembers(TupleTypeSymbol.RestFieldName).FirstOrDefault(), FieldSymbol)
If restField Is Nothing Then
Return -1
End If
If forceContainingSlotsToExist Then
containingSlot = GetOrCreateSlot(restField, containingSlot)
Else
If Not _variableSlot.TryGetValue(New VariableIdentifier(restField, containingSlot), containingSlot) Then
Return -1
End If
End If
containingType = restField.Type.GetTupleUnderlyingTypeOrSelf()
End While
End If
Return containingSlot
End Function
' In C#, we moved this cache to a separate cache held onto by the compilation, so we didn't
' recompute it each time.
'
' This is not so simple in VB, because we'd have to move the cache for members of the
' struct, and we'd need two different caches depending on _trackStructsWithIntrinsicTypedFields.
' So this optimization is not done for now in VB.
Private ReadOnly _isEmptyStructType As New Dictionary(Of NamedTypeSymbol, Boolean)()
Protected Overridable Function IsEmptyStructType(type As TypeSymbol) As Boolean
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType Is Nothing Then
Return False
End If
If Not IsTrackableStructType(namedType) Then
Return False
End If
Dim result As Boolean = False
If _isEmptyStructType.TryGetValue(namedType, result) Then
Return result
End If
' to break cycles
_isEmptyStructType(namedType) = True
For Each field In GetStructInstanceFields(namedType)
If Not IsEmptyStructType(field.Type) Then
_isEmptyStructType(namedType) = False
Return False
End If
Next
_isEmptyStructType(namedType) = True
Return True
End Function
Private Shared Function IsTrackableStructType(symbol As TypeSymbol) As Boolean
If IsNonPrimitiveValueType(symbol) Then
Dim type = TryCast(symbol.OriginalDefinition, NamedTypeSymbol)
Return (type IsNot Nothing) AndAlso Not type.KnownCircularStruct
End If
Return False
End Function
''' <summary> Calculates the flag of being already reported; for structure types
''' the slot may be reported if ALL the children are reported </summary>
Private Function IsSlotAlreadyReported(symbolType As TypeSymbol, slot As Integer) As Boolean
If _alreadyReported(slot) Then
Return True
End If
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return False
End If
If Not IsTrackableStructType(symbolType) Then
Return False
End If
' For structures - check field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
If Not IsSlotAlreadyReported(field.Type, childSlot) Then
Return False
End If
Else
Return False ' slot not created yet
End If
Next
' Seems to be assigned through children
_alreadyReported(slot) = True
Return True
End Function
''' <summary> Marks slot as reported, propagates 'reported' flag to the children if necessary </summary>
Private Sub MarkSlotAsReported(symbolType As TypeSymbol, slot As Integer)
If _alreadyReported(slot) Then
Return
End If
_alreadyReported(slot) = True
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return
End If
If Not IsTrackableStructType(symbolType) Then
Return
End If
' For structures - propagate to field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
MarkSlotAsReported(field.Type, childSlot)
End If
Next
End Sub
''' <summary> Unassign a slot for a regular variable </summary>
Private Sub SetSlotUnassigned(slot As Integer)
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If Me._tryState.HasValue Then
Dim tryState = Me._tryState.Value
SetSlotUnassigned(slot, tryState)
Me._tryState = tryState
End If
SetSlotUnassigned(slot, Me.State)
End Sub
Private Sub SetSlotUnassigned(slot As Integer, ByRef state As LocalState)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
' If the state of the slot is 'assigned' we need to clear it
' and possibly propagate it to all the parents
state.Unassign(slot)
'unassign struct children (if possible)
If IsTrackableStructType(type) Then
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotUnassigned(childSlot, state)
End If
Next
End If
' propagate to parents
While id.ContainingSlot > 0
' check the parent
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
If Not state.IsAssigned(parentSlot) Then
Exit While
End If
' unassign and continue loop
state.Unassign(parentSlot)
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).IsFunctionValue Then
state.Unassign(SlotKind.FunctionValue)
End If
id = parentIdentifier
End While
End Sub
''' <summary>Assign a slot for a regular variable in a given state.</summary>
Private Sub SetSlotAssigned(slot As Integer, ByRef state As LocalState)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If Not state.IsAssigned(slot) Then
' assign this slot
state.Assign(slot)
If IsTrackableStructType(type) Then
' propagate to children
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotAssigned(childSlot, state)
End If
Next
End If
' propagate to parents
While id.ContainingSlot > 0
' check if all parent's children are set
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
Dim parentStructType = GetVariableType(parentSymbol)
' exit while if there is at least one child with a slot which is not assigned
For Each childSymbol In GetStructInstanceFields(parentStructType)
Dim childSlot = GetOrCreateSlot(childSymbol, parentSlot)
If childSlot <> SlotKind.NotTracked AndAlso Not state.IsAssigned(childSlot) Then
Exit While
End If
Next
' otherwise the parent can be set to assigned
state.Assign(parentSlot)
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).IsFunctionValue Then
state.Assign(SlotKind.FunctionValue)
End If
id = parentIdentifier
End While
End If
End Sub
''' <summary>Assign a slot for a regular variable.</summary>
Private Sub SetSlotAssigned(slot As Integer)
SetSlotAssigned(slot, Me.State)
End Sub
''' <summary> Hash structure fields as we may query them many times </summary>
Private _typeToMembersCache As Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol)) = Nothing
Private Function ShouldIgnoreStructField(field As FieldSymbol) As Boolean
If field.IsShared Then
Return True
End If
If Me._trackStructsWithIntrinsicTypedFields Then
' If the flag is set we do not ignore any structure instance fields
Return False
End If
Dim fieldType As TypeSymbol = field.Type
' otherwise of fields of intrinsic type are ignored
If fieldType.IsIntrinsicValueType() Then
Return True
End If
' it the type is a type parameter and also type does NOT guarantee it is
' always a reference type, we ignore the field following Dev11 implementation
If fieldType.IsTypeParameter() Then
Dim typeParam = DirectCast(fieldType, TypeParameterSymbol)
If Not typeParam.IsReferenceType Then
Return True
End If
End If
' We also do NOT ignore all non-private fields
If field.DeclaredAccessibility <> Accessibility.Private Then
Return False
End If
' Do NOT ignore private fields from source
' NOTE: We should do this for all fields, but dev11 ignores private fields from
' metadata, so we need to as well to avoid breaking people. That's why we're
' distinguishing between source and metadata, rather than between the current
' compilation and another compilation.
If field.Dangerous_IsFromSomeCompilationIncludingRetargeting Then
' NOTE: Dev11 ignores fields auto-generated for events
Dim eventOrProperty As Symbol = field.AssociatedSymbol
If eventOrProperty Is Nothing OrElse eventOrProperty.Kind <> SymbolKind.Event Then
Return False
End If
End If
'' If the field is private we don't ignore it if it is a field of a generic struct
If field.ContainingType.IsGenericType Then
Return False
End If
Return True
End Function
Private Function GetStructInstanceFields(type As TypeSymbol) As ImmutableArray(Of FieldSymbol)
Dim result As ImmutableArray(Of FieldSymbol) = Nothing
If _typeToMembersCache Is Nothing OrElse Not _typeToMembersCache.TryGetValue(type, result) Then
' load and add to cache
Dim builder = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each member In type.GetMembersUnordered()
' only fields
If member.Kind = SymbolKind.Field Then
Dim field = DirectCast(member, FieldSymbol)
' Do not report virtual tuple fields.
' They are additional aliases to the fields of the underlying struct or nested extensions.
' and as such are already accounted for via the nonvirtual fields.
If field.IsVirtualTupleField Then
Continue For
End If
' only instance fields
If Not ShouldIgnoreStructField(field) Then
' NOTE: DO NOT skip fields of intrinsic types if _trackStructsWithIntrinsicTypedFields is True
builder.Add(field)
End If
End If
Next
result = builder.ToImmutableAndFree()
If _typeToMembersCache Is Nothing Then
_typeToMembersCache = New Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol))
End If
_typeToMembersCache.Add(type, result)
End If
Return result
End Function
Private Shared Function GetVariableType(symbol As Symbol) As TypeSymbol
Select Case symbol.Kind
Case SymbolKind.Local
Return DirectCast(symbol, LocalSymbol).Type
Case SymbolKind.RangeVariable
Return DirectCast(symbol, RangeVariableSymbol).Type
Case SymbolKind.Field
Return DirectCast(symbol, FieldSymbol).Type
Case SymbolKind.Parameter
Return DirectCast(symbol, ParameterSymbol).Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End Function
Protected Sub SetSlotState(slot As Integer, assigned As Boolean)
Debug.Assert(slot <> SlotKind.Unreachable)
If slot = SlotKind.NotTracked Then
Return
ElseIf slot = SlotKind.FunctionValue Then
' Function value slot is treated in a special way. For example it does not have Symbol assigned
' Just do a simple assign/unassign
If assigned Then
Me.State.Assign(slot)
Else
Me.State.Unassign(slot)
End If
Else
' The rest should be a regular slot
If assigned Then
SetSlotAssigned(slot)
Else
SetSlotUnassigned(slot)
End If
End If
End Sub
#End Region
#Region "Assignments: Check and Report"
''' <summary>
''' Check that the given variable is definitely assigned. If not, produce an error.
''' </summary>
Protected Sub CheckAssigned(symbol As Symbol, node As SyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
If symbol IsNot Nothing Then
Dim local = TryCast(symbol, LocalSymbol)
If local IsNot Nothing AndAlso local.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals
Return
End If
' 'local' can be a pseudo-local representing a set of real locals
If local IsNot Nothing AndAlso local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
Dim ambiguous = DirectCast(local, AmbiguousLocalsPseudoSymbol)
' Ambiguous implicit receiver is always considered to be assigned
VisitAmbiguousLocalSymbol(ambiguous)
' Note reads of locals
For Each subLocal In ambiguous.Locals
NoteRead(subLocal)
Next
Else
Dim slot As Integer = GetOrCreateSlot(symbol)
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If slot >= SlotKind.FirstAvailable AndAlso Me.State.Reachable AndAlso Not Me.State.IsAssigned(slot) Then
ReportUnassigned(symbol, node, rwContext)
End If
NoteRead(symbol)
End If
End If
End Sub
''' <summary> Version of CheckAssigned for bound field access </summary>
Private Sub CheckAssigned(fieldAccess As BoundFieldAccess, node As SyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
Dim unassignedSlot As Integer
If Me.State.Reachable AndAlso Not IsAssigned(fieldAccess, unassignedSlot) Then
ReportUnassigned(fieldAccess.FieldSymbol, node, rwContext, unassignedSlot, fieldAccess)
End If
NoteRead(fieldAccess)
End Sub
Protected Overridable Sub VisitAmbiguousLocalSymbol(ambiguous As AmbiguousLocalsPseudoSymbol)
End Sub
Protected Overrides Sub VisitLvalue(node As BoundExpression, Optional dontLeaveRegion As Boolean = False)
MyBase.VisitLvalue(node, True) ' Don't leave region
If node.Kind = BoundKind.Local Then
Dim symbol As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If symbol.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
VisitAmbiguousLocalSymbol(DirectCast(symbol, AmbiguousLocalsPseudoSymbol))
End If
End If
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
''' <summary> Check node for being assigned, return the value of unassigned slot in unassignedSlot </summary>
Private Function IsAssigned(node As BoundExpression, ByRef unassignedSlot As Integer) As Boolean
unassignedSlot = SlotKind.NotTracked
If IsEmptyStructType(node.Type) Then
Return True
End If
Select Case node.Kind
Case BoundKind.MeReference
unassignedSlot = VariableSlot(MeParameter)
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind <> LocalDeclarationKind.AmbiguousLocals Then
unassignedSlot = VariableSlot(local)
Else
' We never report ambiguous locals pseudo-symbol as unassigned,
unassignedSlot = SlotKind.NotTracked
VisitAmbiguousLocalSymbol(DirectCast(local, AmbiguousLocalsPseudoSymbol))
End If
Case BoundKind.RangeVariable
' range variables are always assigned
unassignedSlot = -1
Return True
Case BoundKind.Parameter
unassignedSlot = VariableSlot(DirectCast(node, BoundParameter).ParameterSymbol)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If Not FieldAccessMayRequireTracking(fieldAccess) OrElse IsAssigned(fieldAccess.ReceiverOpt, unassignedSlot) Then
Return True
End If
' NOTE: unassignedSlot must have been set by previous call to IsAssigned(...)
unassignedSlot = GetOrCreateSlot(fieldAccess.FieldSymbol, unassignedSlot)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return IsAssigned(substitute, unassignedSlot)
End If
unassignedSlot = SlotKind.NotTracked
Case Else
' The value is a method call return value or something else we can assume is assigned.
unassignedSlot = SlotKind.NotTracked
End Select
Return Me.State.IsAssigned(unassignedSlot)
End Function
''' <summary>
''' Property controls Roslyn data flow analysis features which are disabled in command-line
''' compiler mode to maintain backward compatibility (mostly diagnostics not reported by Dev11),
''' but *enabled* in flow analysis API
''' </summary>
Protected Overridable ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Specifies if the analysis should process compiler generated locals.
'''
''' Note that data flow API should never report compiler generated variables
''' as well as those should not generate any diagnostics (like being unassigned, etc...).
'''
''' But when the analysis is used for iterators or async captures it should process
''' compiler generated locals as well...
''' </summary>
Protected Overridable ReadOnly Property ProcessCompilerGeneratedLocals As Boolean
Get
Return False
End Get
End Property
Private Function GetUnassignedSymbolFirstLocation(sym As Symbol, boundFieldAccess As BoundFieldAccess) As Location
Select Case sym.Kind
Case SymbolKind.Parameter
Return Nothing
Case SymbolKind.RangeVariable
Return Nothing
Case SymbolKind.Local
Dim locations As ImmutableArray(Of Location) = sym.Locations
Return If(locations.IsEmpty, Nothing, locations(0))
Case SymbolKind.Field
Debug.Assert(boundFieldAccess IsNot Nothing)
If sym.IsShared Then
Return Nothing
End If
Dim receiver As BoundExpression = boundFieldAccess.ReceiverOpt
Debug.Assert(receiver IsNot Nothing)
Select Case receiver.Kind
Case BoundKind.Local
Return GetUnassignedSymbolFirstLocation(DirectCast(receiver, BoundLocal).LocalSymbol, Nothing)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(receiver, BoundFieldAccess)
Return GetUnassignedSymbolFirstLocation(fieldAccess.FieldSymbol, fieldAccess)
Case Else
Return Nothing
End Select
Case Else
Debug.Assert(False, "Why is this reachable?")
Return Nothing
End Select
End Function
''' <summary>
''' Report a given variable as not definitely assigned. Once a variable has been so
''' reported, we suppress further reports of that variable.
''' </summary>
Protected Overridable Sub ReportUnassigned(sym As Symbol,
node As SyntaxNode,
rwContext As ReadWriteContext,
Optional slot As Integer = SlotKind.NotTracked,
Optional boundFieldAccess As BoundFieldAccess = Nothing)
If slot < SlotKind.FirstAvailable Then
slot = VariableSlot(sym)
End If
If slot >= Me._alreadyReported.Capacity Then
_alreadyReported.EnsureCapacity(Me.nextVariableSlot)
End If
If sym.Kind = SymbolKind.Parameter Then
' Because there are no Out parameters in VB, general workflow should not hit this point;
' but in region analysis parameters are being unassigned, so it is reachable
Return
End If
If sym.Kind = SymbolKind.RangeVariable Then
' Range variables are always assigned for the purpose of error reporting.
Return
End If
Debug.Assert(sym.Kind = SymbolKind.Local OrElse sym.Kind = SymbolKind.Field)
Dim localOrFieldType As TypeSymbol
Dim isFunctionValue As Boolean
Dim isStaticLocal As Boolean
Dim isImplicitlyDeclared As Boolean = False
If sym.Kind = SymbolKind.Local Then
Dim locSym = DirectCast(sym, LocalSymbol)
localOrFieldType = locSym.Type
isFunctionValue = locSym.IsFunctionValue AndAlso EnableBreakingFlowAnalysisFeatures
isStaticLocal = locSym.IsStatic
isImplicitlyDeclared = locSym.IsImplicitlyDeclared
Else
isFunctionValue = False
isStaticLocal = False
localOrFieldType = DirectCast(sym, FieldSymbol).Type
End If
If Not IsSlotAlreadyReported(localOrFieldType, slot) Then
Dim warning As ERRID = Nothing
' NOTE: When a variable is being used before declaration VB generates ERR_UseOfLocalBeforeDeclaration1
' NOTE: error, thus we don't want to generate redundant warning; we base such an analysis on node
' NOTE: and symbol locations
Dim firstLocation As Location = GetUnassignedSymbolFirstLocation(sym, boundFieldAccess)
If isImplicitlyDeclared OrElse firstLocation Is Nothing OrElse firstLocation.SourceSpan.Start < node.SpanStart Then
' Because VB does not support out parameters, only locals OR fields of local structures can be unassigned.
If localOrFieldType IsNot Nothing AndAlso Not isStaticLocal Then
If localOrFieldType.IsIntrinsicValueType OrElse localOrFieldType.IsReferenceType Then
If localOrFieldType.IsIntrinsicValueType AndAlso Not isFunctionValue Then
warning = Nothing
Else
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRef, ERRID.WRN_DefAsgUseNullRef)
End If
ElseIf localOrFieldType.IsValueType Then
' This is only reported for structures with reference type fields.
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRefStr, ERRID.WRN_DefAsgUseNullRefStr)
Else
Debug.Assert(localOrFieldType.IsTypeParameter)
End If
If warning <> Nothing Then
Me.diagnostics.Add(warning, node.GetLocation(), If(sym.Name, "dummy"))
End If
End If
MarkSlotAsReported(localOrFieldType, slot)
End If
End If
End Sub
Private Sub CheckAssignedFunctionValue(local As LocalSymbol, node As SyntaxNode)
If Not Me.State.FunctionAssignedValue AndAlso Not _seenOnErrorOrResume Then
Dim type As TypeSymbol = local.Type
' NOTE: Dev11 does NOT report warning on user-defined empty value types
' Special case: We specifically want to give a warning if the user doesn't return from a WinRT AddHandler.
' NOTE: Strictly speaking, dev11 actually checks whether the return type is EventRegistrationToken (see IsWinRTEventAddHandler),
' but the conditions should be equivalent (i.e. return EventRegistrationToken if and only if WinRT).
If EnableBreakingFlowAnalysisFeatures OrElse Not type.IsValueType OrElse type.IsIntrinsicOrEnumType OrElse Not IsEmptyStructType(type) OrElse
(Me.MethodSymbol.MethodKind = MethodKind.EventAdd AndAlso DirectCast(Me.MethodSymbol.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent) Then
ReportUnassignedFunctionValue(local, node)
End If
End If
End Sub
Private Sub ReportUnassignedFunctionValue(local As LocalSymbol, node As SyntaxNode)
If Not _alreadyReported(SlotKind.FunctionValue) Then
Dim type As TypeSymbol = Nothing
Dim method = Me.MethodSymbol
type = method.ReturnType
If type IsNot Nothing AndAlso
Not (method.IsIterator OrElse
(method.IsAsync AndAlso type.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)))) Then
Dim warning As ERRID = Nothing
Dim localName As String = GetFunctionLocalName(method, local)
type = type.GetEnumUnderlyingTypeOrSelf
' Actual warning depends on whether the local is a function,
' property, or operator value versus reference type.
If type.IsIntrinsicValueType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpVal1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropVal1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncVal1
End Select
ElseIf type.IsReferenceType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpRef1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
ElseIf type.TypeKind = TypeKind.TypeParameter Then
' IsReferenceType was false, so this type parameter was not known to be a reference type.
' Following past practice, no warning is given in this case.
Else
Debug.Assert(type.IsValueType)
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' no warning is given in this case.
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case MethodKind.EventAdd
' In Dev11, there wasn't time to change the syntax of AddHandler to allow the user
' to specify a return type (necessarily, EventRegistrationToken) for WinRT events.
' DevDiv #376690 reflects the fact that this leads to an incredibly confusing user
' experience if nothing is return: no diagnostics are reported, but RemoveHandler
' statements will silently fail. To prompt the user, (1) warn if there is no
' explicit return, and (2) modify the error message to say "AddHandler As
' EventRegistrationToken" to hint at the nature of the problem.
' Update: Dev11 just mangles an existing error message, but we'll introduce a new,
' clearer, one.
warning = ERRID.WRN_DefAsgNoRetValWinRtEventVal1
localName = MethodSymbol.AssociatedSymbol.Name
Case Else
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
End If
If warning <> Nothing Then
Debug.Assert(localName IsNot Nothing)
Me.diagnostics.Add(warning, node.GetLocation(), localName)
End If
End If
_alreadyReported(SlotKind.FunctionValue) = True
End If
End Sub
Private Shared Function GetFunctionLocalName(method As MethodSymbol, local As LocalSymbol) As String
Select Case method.MethodKind
Case MethodKind.LambdaMethod
Return StringConstants.AnonymousMethodName
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' The operator's function local is op_<something> and not
' VB's operator name, so we need to take the identifier token
' directly
Dim operatorBlock = DirectCast(DirectCast(local.ContainingSymbol, SourceMemberMethodSymbol).BlockSyntax, OperatorBlockSyntax)
Return operatorBlock.OperatorStatement.OperatorToken.Text
Case Else
Return If(local.Name, method.Name)
End Select
End Function
''' <summary>
''' Mark a variable as assigned (or unassigned).
''' </summary>
Protected Overridable Sub Assign(node As BoundNode, value As BoundExpression, Optional assigned As Boolean = True)
Select Case node.Kind
Case BoundKind.LocalDeclaration
Dim local = DirectCast(node, BoundLocalDeclaration)
Debug.Assert(local.InitializerOpt Is value OrElse local.InitializedByAsNew)
Dim symbol = local.LocalSymbol
Dim slot As Integer = GetOrCreateSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
' Note write if the local has an initializer or if it is part of an as-new.
If assigned AndAlso (value IsNot Nothing OrElse local.InitializedByAsNew) Then NoteWrite(symbol, value)
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Dim forStatement = DirectCast(node, BoundForStatement)
Dim symbol = forStatement.DeclaredOrInferredLocalOpt
Debug.Assert(symbol IsNot Nothing)
Dim slot As Integer = GetOrCreateSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
Case BoundKind.Local
Dim local = DirectCast(node, BoundLocal)
Dim symbol = local.LocalSymbol
If symbol.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals.
Return
End If
' Regular variable
Dim slot As Integer = GetOrCreateSlot(symbol)
SetSlotState(slot, assigned)
If symbol.IsFunctionValue Then
SetSlotState(SlotKind.FunctionValue, assigned)
End If
If assigned Then
NoteWrite(symbol, value)
End If
Case BoundKind.Parameter
Dim local = DirectCast(node, BoundParameter)
Dim symbol = local.ParameterSymbol
Dim slot As Integer = GetOrCreateSlot(symbol)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(symbol, value)
Case BoundKind.MeReference
' var local = node as BoundThisReference;
Dim slot As Integer = GetOrCreateSlot(MeParameter)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(MeParameter, value)
Case BoundKind.FieldAccess, BoundKind.PropertyAccess
Dim expression = DirectCast(node, BoundExpression)
Dim slots As SlotCollection = MakeSlotsForExpression(expression)
For i = 0 To slots.Count - 1
SetSlotState(slots(i), assigned)
Next
slots.Free()
If assigned Then NoteWrite(expression, value)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Assign(substitute, value, assigned)
End If
Case BoundKind.ByRefArgumentWithCopyBack
Assign(DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument, value, assigned)
Case Else
' Other kinds of left-hand-sides either represent things not tracked (e.g. array elements)
' or errors that have been reported earlier (e.g. assignment to a unary increment)
End Select
End Sub
#End Region
#Region "Try statements"
' When assignments happen inside a region, they are treated as UN-assignments.
' Generally this is enough.
'
' The tricky part is that any instruction in Try/Catch/Finally must be considered as potentially throwing.
' Even if a subsequent write outside of the region may kill an assignment inside the region, it cannot prevent escape of
' the previous assignment.
'
' === Example:
'
' Dim x as integer = 0
' Try
' [| region starts here
' x = 1
' Blah() ' <- this statement may throw. (any instruction can).
' |] region ends here
' x = 2 ' <- it may seem that this assignment kills one above, where in fact "x = 1" can easily escape.
' Finally
' SomeUse(x) ' we can see side effects of "x = 1" here
' End Try
'
' As a result, when dealing with exception handling flows we need to maintain a separate state
' that collects UN-assignments only and is not affected by subsequent assignments.
Private _tryState As OptionalState
Protected Overrides Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef _tryState As LocalState)
If Me.TrackUnassignments Then
' store original try state
Dim oldTryState As OptionalState = Me._tryState
' start with AllBitsSet (means there were no assignments)
Me._tryState = AllBitsSet()
' visit try block. Any assignment inside the region will UN-assign corresponding bit in the tryState.
MyBase.VisitTryBlock(tryBlock, node, _tryState)
' merge resulting tryState into tryState that we were given.
Me.IntersectWith(_tryState, Me._tryState.Value)
' restore and merge old state with new changes.
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
MyBase.VisitTryBlock(tryBlock, node, _tryState)
End If
End Sub
Protected Overrides Sub VisitCatchBlock(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As OptionalState = Me._tryState
Me._tryState = AllBitsSet()
Me.VisitCatchBlockInternal(catchBlock, finallyState)
Me.IntersectWith(finallyState, Me._tryState.Value)
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
Me.VisitCatchBlockInternal(catchBlock, finallyState)
End If
End Sub
Private Sub VisitCatchBlockInternal(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
Dim local = catchBlock.LocalOpt
If local IsNot Nothing Then
GetOrCreateSlot(local)
End If
Dim exceptionSource = catchBlock.ExceptionSourceOpt
If exceptionSource IsNot Nothing Then
Assign(exceptionSource, value:=Nothing, assigned:=True)
End If
MyBase.VisitCatchBlock(catchBlock, finallyState)
End Sub
Protected Overrides Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef unsetInFinally As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As OptionalState = Me._tryState
Me._tryState = AllBitsSet()
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
Me.IntersectWith(unsetInFinally, Me._tryState.Value)
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
End If
End Sub
#End Region
Protected Overrides Function ReachableState() As LocalState
Return New LocalState(BitVector.Empty)
End Function
Private Sub EnterParameters(parameters As ImmutableArray(Of ParameterSymbol))
For Each parameter In parameters
EnterParameter(parameter)
Next
End Sub
Protected Overridable Sub EnterParameter(parameter As ParameterSymbol)
' this code has no effect except in the region analysis APIs, which assign
' variable slots to all parameters.
Dim slot As Integer = VariableSlot(parameter)
If slot >= SlotKind.FirstAvailable Then
Me.State.Assign(slot)
End If
NoteWrite(parameter, Nothing)
End Sub
Private Sub LeaveParameters(parameters As ImmutableArray(Of ParameterSymbol))
If Me.State.Reachable Then
For Each parameter In parameters
LeaveParameter(parameter)
Next
End If
End Sub
Private Sub LeaveParameter(parameter As ParameterSymbol)
If parameter.IsByRef Then
Dim slot = VariableSlot(parameter)
If Not Me.State.IsAssigned(slot) Then
ReportUnassignedByRefParameter(parameter)
End If
NoteRead(parameter)
End If
End Sub
Protected Overrides Function UnreachableState() As LocalState
' at this point we don't know what size of the bitarray to use, so we only set
' 'reachable' flag which mean 'all bits are set' in intersect/union
Return New LocalState(UnreachableBitsSet)
End Function
Protected Overrides Function AllBitsSet() As LocalState
Dim result = New LocalState(BitVector.AllSet(nextVariableSlot))
result.Unassign(SlotKind.Unreachable)
Return result
End Function
Protected Overrides Sub VisitLocalInReadWriteContext(node As BoundLocal, rwContext As ReadWriteContext)
MyBase.VisitLocalInReadWriteContext(node, rwContext)
CheckAssigned(node.LocalSymbol, node.Syntax, rwContext)
End Sub
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
CheckAssigned(node.LocalSymbol, node.Syntax, ReadWriteContext.None)
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
' Sometimes query expressions refer to query range variable just to
' copy its value to a new compound variable. There is no reference
' to the range variable in code and, from user point of view, there is
' no access to it.
If Not node.WasCompilerGenerated Then
CheckAssigned(node.RangeVariable, node.Syntax, ReadWriteContext.None)
End If
Return Nothing
End Function
' Should this local variable be considered assigned at first? It is if in the set of initially
' assigned variables, or else the current state is not reachable.
Protected Function ConsiderLocalInitiallyAssigned(variable As LocalSymbol) As Boolean
Return Not Me.State.Reachable OrElse
initiallyAssignedVariables IsNot Nothing AndAlso initiallyAssignedVariables.Contains(variable)
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned = DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax.Parent, node.InitializerOpt, placeholder)
Dim local As LocalSymbol = node.LocalSymbol
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
SetPlaceholderSubstitute(placeholder, New BoundLocal(node.Syntax, local, local.Type))
End If
' Create a slot for the declared variable to be able to track it.
Dim slot As Integer = GetOrCreateSlot(local)
'If initializer is a lambda, we need to treat the local as assigned within the lambda.
Assign(node, node.InitializerOpt,
ConsiderLocalInitiallyAssigned(local) OrElse
variableIsUsedDirectlyAndIsAlwaysAssigned OrElse
TreatTheLocalAsAssignedWithinTheLambda(local, node.InitializerOpt))
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
' Assign must be called after the initializer is analyzed, because the variable needs to be
' consider unassigned which the initializer is being analyzed.
MyBase.VisitLocalDeclaration(node)
End If
AssignLocalOnDeclaration(local, node)
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function TreatTheLocalAsAssignedWithinTheLambda(local As LocalSymbol, right As BoundExpression) As Boolean
Return IsConvertedLambda(right)
End Function
Private Shared Function IsConvertedLambda(value As BoundExpression) As Boolean
If value Is Nothing Then
Return False
End If
Do
Select Case value.Kind
Case BoundKind.Lambda
Return True
Case BoundKind.Conversion
value = DirectCast(value, BoundConversion).Operand
Case BoundKind.DirectCast
value = DirectCast(value, BoundDirectCast).Operand
Case BoundKind.TryCast
value = DirectCast(value, BoundTryCast).Operand
Case BoundKind.Parenthesized
value = DirectCast(value, BoundParenthesized).Expression
Case Else
Return False
End Select
Loop
End Function
Friend Overridable Sub AssignLocalOnDeclaration(local As LocalSymbol, node As BoundLocalDeclaration)
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
Assign(node, node.InitializerOpt)
End If
End Sub
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
' Implicitly declared local variables don't have LocalDeclarations nodes for them. Thus,
' we need to create slots for any implicitly declared local variables in this block.
' For flow analysis purposes, we treat an implicit declared local as equivalent to a variable declared at the
' start of the method body (this block) with no initializer.
Dim localVariables = node.Locals
For Each local In localVariables
If local.IsImplicitlyDeclared Then
SetSlotState(GetOrCreateSlot(local), ConsiderLocalInitiallyAssigned(local))
End If
Next
Return MyBase.VisitBlock(node)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Dim oldPending As SavedPending = SavePending()
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State
Me.SetState(If(finalState.Reachable, finalState.Clone(), Me.AllBitsSet()))
Me.State.Assigned(SlotKind.FunctionValue) = False
Dim save_alreadyReportedFunctionValue = _alreadyReported(SlotKind.FunctionValue)
_alreadyReported(SlotKind.FunctionValue) = False
EnterParameters(node.LambdaSymbol.Parameters)
VisitBlock(node.Body)
LeaveParameters(node.LambdaSymbol.Parameters)
Me.symbol = oldSymbol
_alreadyReported(SlotKind.FunctionValue) = save_alreadyReportedFunctionValue
Me.State.Assigned(SlotKind.FunctionValue) = True
RestorePending(oldPending)
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State.Clone()
VisitRvalue(node.Expression)
Me.symbol = oldSymbol
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
VisitRvalue(node.LastOperator)
Return Nothing
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
VisitRvalue(node.Source)
Return Nothing
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
VisitRvalue(node.ConversionCall)
Return Nothing
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
If node.CapturedGroupOpt IsNot Nothing Then
VisitRvalue(node.CapturedGroupOpt)
End If
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
VisitRvalue(node.Value)
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
If Not node.WasCompilerGenerated Then
CheckAssigned(node.ParameterSymbol, node.Syntax)
End If
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim result = MyBase.VisitFieldAccess(node)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, ReadWriteContext.None)
End If
Return result
End Function
Protected Overrides Sub VisitFieldAccessInReadWriteContext(node As BoundFieldAccess, rwContext As ReadWriteContext)
MyBase.VisitFieldAccessInReadWriteContext(node, rwContext)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, rwContext)
End If
End Sub
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim left As BoundExpression = node.Left
'If right expression is a lambda, we need to treat the left side as assigned within the lambda.
Dim treatLocalAsAssigned As Boolean = False
If left.Kind = BoundKind.Local Then
treatLocalAsAssigned = TreatTheLocalAsAssignedWithinTheLambda(
DirectCast(left, BoundLocal).LocalSymbol, node.Right)
End If
If treatLocalAsAssigned Then
Assign(left, node.Right)
End If
MyBase.VisitAssignmentOperator(node)
If Not treatLocalAsAssigned Then
Assign(left, node.Right)
End If
Return Nothing
End Function
Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean
Get
Return True
End Get
End Property
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
MyBase.VisitRedimClause(node)
Assign(node.Operand, Nothing)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
MyBase.VisitReferenceAssignment(node)
Assign(node.ByRefLocal, node.LValue)
Return Nothing
End Function
Protected Overrides Sub VisitForControlInitialization(node As BoundForToStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, node.InitialValue)
End Sub
Protected Overrides Sub VisitForControlInitialization(node As BoundForEachStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, Nothing)
End Sub
Protected Overrides Sub VisitForStatementVariableDeclaration(node As BoundForStatement)
' if the for each statement declared a variable explicitly or by using local type inference we'll
' need to create a new slot for the new variable that is initially unassigned.
If node.DeclaredOrInferredLocalOpt IsNot Nothing Then
Dim slot As Integer = GetOrCreateSlot(node.DeclaredOrInferredLocalOpt) 'not initially assigned
Assign(node, Nothing, ConsiderLocalInitiallyAssigned(node.DeclaredOrInferredLocalOpt))
End If
End Sub
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
MyBase.VisitAnonymousTypeCreationExpression(node)
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Me.SetPlaceholderSubstitute(node.ExpressionPlaceholder, node.DraftPlaceholderSubstitute)
MyBase.VisitWithStatement(node)
Me.RemovePlaceholderSubstitute(node.ExpressionPlaceholder)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
If node.ResourceList.IsDefaultOrEmpty Then
' only an expression. Let the base class' implementation deal with digging into the expression
Return MyBase.VisitUsingStatement(node)
End If
' all locals are considered initially assigned, even if the initialization expression is missing in source (error case)
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
Dim local = variableDeclaration.LocalSymbol
Dim slot = GetOrCreateSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
Next
Else
Dim local = DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol
Dim slot = GetOrCreateSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
End If
Next
Dim result = MyBase.VisitUsingStatement(node)
' all locals are being read in the finally block.
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
NoteRead(variableDeclaration.LocalSymbol)
Next
Else
NoteRead(DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol)
End If
Next
Return result
End Function
Protected Overridable ReadOnly Property IgnoreOutSemantics As Boolean
Get
Return True
End Get
End Property
Protected NotOverridable Overrides Sub VisitArgument(arg As BoundExpression, p As ParameterSymbol)
Debug.Assert(arg IsNot Nothing)
If p.IsByRef Then
If p.IsOut And Not Me.IgnoreOutSemantics Then
VisitLvalue(arg)
Else
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
End If
Else
VisitRvalue(arg)
End If
End Sub
Protected Overrides Sub WriteArgument(arg As BoundExpression, isOut As Boolean)
If Not isOut Then
CheckAssignedFromArgumentWrite(arg, arg.Syntax)
End If
Assign(arg, Nothing)
MyBase.WriteArgument(arg, isOut)
End Sub
Protected Sub CheckAssignedFromArgumentWrite(expr As BoundExpression, node As SyntaxNode)
If Not Me.State.Reachable Then
Return
End If
Select Case expr.Kind
Case BoundKind.Local
CheckAssigned(DirectCast(expr, BoundLocal).LocalSymbol, node)
Case BoundKind.Parameter
CheckAssigned(DirectCast(expr, BoundParameter).ParameterSymbol, node)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(expr, BoundFieldAccess)
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If FieldAccessMayRequireTracking(fieldAccess) Then
CheckAssigned(fieldAccess, node, ReadWriteContext.ByRefArgument)
End If
Case BoundKind.EventAccess
Throw ExceptionUtilities.UnexpectedValue(expr.Kind) ' TODO: is this reachable at all?
Case BoundKind.MeReference,
BoundKind.MyClassReference,
BoundKind.MyBaseReference
CheckAssigned(MeParameter, node)
End Select
End Sub
Protected Overrides Sub VisitLateBoundArgument(arg As BoundExpression, isByRef As Boolean)
If isByRef Then
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
Else
VisitRvalue(arg)
End If
End Sub
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
If Not node.IsEndOfMethodReturn Then
' We should mark it as set disregarding whether or not there is an expression; if there
' is no expression, error 30654 will be generated which in Dev10 suppresses this error
SetSlotState(SlotKind.FunctionValue, True)
Else
Dim functionLocal = TryCast(node.ExpressionOpt, BoundLocal)
If functionLocal IsNot Nothing Then
CheckAssignedFunctionValue(functionLocal.LocalSymbol, node.Syntax)
End If
End If
MyBase.VisitReturnStatement(node)
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
''' <summary>
''' A variable declared with As New can be considered assigned before the initializer is executed in case the variable
''' is a value type. The reason is that in this case the initialization happens in place (not in a temporary) and
''' the variable already got the object creation expression assigned.
''' </summary>
Private Function DeclaredVariableIsAlwaysAssignedBeforeInitializer(syntax As SyntaxNode, boundInitializer As BoundExpression,
<Out> ByRef placeholder As BoundValuePlaceholderBase) As Boolean
placeholder = Nothing
If boundInitializer IsNot Nothing AndAlso
(boundInitializer.Kind = BoundKind.ObjectCreationExpression OrElse boundInitializer.Kind = BoundKind.NewT) Then
Dim boundInitializerBase = DirectCast(boundInitializer, BoundObjectCreationExpressionBase).InitializerOpt
If boundInitializerBase IsNot Nothing AndAlso boundInitializerBase.Kind = BoundKind.ObjectInitializerExpression Then
Dim objectInitializer = DirectCast(boundInitializerBase, BoundObjectInitializerExpression)
If syntax IsNot Nothing AndAlso syntax.Kind = SyntaxKind.VariableDeclarator Then
Dim declarator = DirectCast(syntax, VariableDeclaratorSyntax)
If declarator.AsClause IsNot Nothing AndAlso declarator.AsClause.Kind = SyntaxKind.AsNewClause Then
placeholder = objectInitializer.PlaceholderOpt
Return Not objectInitializer.CreateTemporaryLocalForInitialization
End If
End If
End If
End If
Return False
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned =
DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax, node.Initializer, placeholder)
Dim declarations As ImmutableArray(Of BoundLocalDeclaration) = node.LocalDeclarations
If declarations.IsEmpty Then
Return Nothing
End If
' An initializer might access the declared variables in the initializer and therefore need to create a slot to
' track them
For Each localDeclaration In declarations
GetOrCreateSlot(localDeclaration.LocalSymbol)
Next
' NOTE: in case 'variableIsUsedDirectlyAndIsAlwaysAssigned' is set it must be
' Dim a[, b, ...] As New Struct(...) With { ... }.
'
' In this case Roslyn (following Dev10/Dev11) consecutively calls constructors
' and executes initializers for all declared variables. Thus, when the first
' initializer is being executed, all other locals are not assigned yet.
'
' This behavior is emulated below by assigning the first local and visiting
' the initializer before assigning all the other locals. We don't really need
' to revisit initializer after because all errors/warnings will be property
' reported in the first visit.
Dim localToUseAsSubstitute As LocalSymbol = CreateLocalSymbolForVariables(declarations)
' process the first local declaration once
Dim localDecl As BoundLocalDeclaration = declarations(0)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
' in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
' if needed, replace the placeholders with the bound local for the current declared variable.
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.SetPlaceholderSubstitute(placeholder, New BoundLocal(localDecl.Syntax, localToUseAsSubstitute, localToUseAsSubstitute.Type))
End If
VisitRvalue(node.Initializer)
Visit(localDecl) ' TODO: do we really need that?
' Visit all other declarations
For index = 1 To declarations.Length - 1
localDecl = declarations(index)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
'in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
Visit(localDecl) ' TODO: do we really need that?
Next
' We also need to mark all
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol
Debug.Assert(declarations.Length > 0)
Return declarations(0).LocalSymbol
End Function
Protected Overrides Sub VisitObjectCreationExpressionInitializer(node As BoundObjectInitializerExpressionBase)
Dim resetPlaceholder As Boolean = node IsNot Nothing AndAlso
node.Kind = BoundKind.ObjectInitializerExpression AndAlso
DirectCast(node, BoundObjectInitializerExpression).CreateTemporaryLocalForInitialization
If resetPlaceholder Then
Me.SetPlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt, Nothing) ' Override substitute
End If
MyBase.VisitObjectCreationExpressionInitializer(node)
If resetPlaceholder Then
Me.RemovePlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt)
End If
End Sub
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
_seenOnErrorOrResume = True
Return MyBase.VisitOnErrorStatement(node)
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
_seenOnErrorOrResume = True
Return MyBase.VisitResumeStatement(node)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.PooledObjects
#If DEBUG Then
' We use a struct rather than a class to represent the state for efficiency
' for data flow analysis, with 32 bits of data inline. Merely copying the state
' variable causes the first 32 bits to be cloned, as they are inline. This can
' hide a plethora of errors that would only be exhibited in programs with more
' than 32 variables to be tracked. However, few of our tests have that many
' variables.
'
' To help diagnose these problems, we use the preprocessor symbol REFERENCE_STATE
' to cause the data flow state be a class rather than a struct. When it is a class,
' this category of problems would be exhibited in programs with a small number of
' tracked variables. But it is slower, so we only do it in DEBUG mode.
#Const REFERENCE_STATE = True
#End If
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
#If REFERENCE_STATE Then
Imports OptionalState = Microsoft.CodeAnalysis.[Optional](Of Microsoft.CodeAnalysis.VisualBasic.DataFlowPass.LocalState)
#Else
Imports OptionalState = System.Nullable(Of Microsoft.CodeAnalysis.VisualBasic.DataFlowPass.LocalState)
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class DataFlowPass
Inherits AbstractFlowPass(Of LocalState)
Public Enum SlotKind
''' <summary>
''' Special slot for untracked variables
''' </summary>
NotTracked = -1
''' <summary>
''' Special slot for tracking whether code is reachable
''' </summary>
Unreachable = 0
''' <summary>
''' Special slot for tracking the implicit local for the function return value
''' </summary>
FunctionValue = 1
''' <summary>
''' The first available slot for variables
''' </summary>
''' <remarks></remarks>
FirstAvailable = 2
End Enum
''' <summary>
''' Some variables that should be considered initially assigned. Used for region analysis.
''' </summary>
Protected ReadOnly initiallyAssignedVariables As HashSet(Of Symbol)
''' <summary>
''' Defines whether or not fields of intrinsic type should be tracked. Such fields should
''' not be tracked for error reporting purposes, but should be tracked for region flow analysis
''' </summary>
Private ReadOnly _trackStructsWithIntrinsicTypedFields As Boolean
''' <summary>
''' Variables that were used anywhere, in the sense required to suppress warnings about unused variables.
''' </summary>
Private ReadOnly _unusedVariables As HashSet(Of LocalSymbol) = New HashSet(Of LocalSymbol)()
''' <summary>
''' Variables that were initialized or written anywhere.
''' </summary>
Private ReadOnly _writtenVariables As HashSet(Of Symbol) = New HashSet(Of Symbol)()
''' <summary>
''' A mapping from local variables to the index of their slot in a flow analysis local state.
''' WARNING: if variable identifier maps into SlotKind.NotTracked, it may mean that VariableIdentifier
''' is a structure without traceable fields. This mapping is created in MakeSlotImpl(...)
''' </summary>
Private ReadOnly _variableSlot As Dictionary(Of VariableIdentifier, Integer) = New Dictionary(Of VariableIdentifier, Integer)()
''' <summary>
''' A mapping from the local variable slot to the symbol for the local variable itself. This is used in the
''' implementation of region analysis (support for extract method) to compute the set of variables "always
''' assigned" in a region of code.
''' </summary>
Protected variableBySlot As VariableIdentifier() = New VariableIdentifier(10) {}
''' <summary>
''' Variable slots are allocated to local variables sequentially and never reused. This is
''' the index of the next slot number to use.
''' </summary>
Protected nextVariableSlot As Integer = SlotKind.FirstAvailable
''' <summary>
''' Tracks variables for which we have already reported a definite assignment error. This
''' allows us to report at most one such error per variable.
''' </summary>
Private _alreadyReported As BitVector
''' <summary>
''' Did we see [On Error] or [Resume] statement? Used to suppress some diagnostics.
''' </summary>
Private _seenOnErrorOrResume As Boolean
Protected _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException As Boolean = False ' By default, just let the original exception to bubble up.
Friend Sub New(info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean, Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, suppressConstExpressionsSupport)
Me.initiallyAssignedVariables = Nothing
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo,
suppressConstExpressionsSupport As Boolean,
Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing,
Optional trackUnassignments As Boolean = False,
Optional trackStructsWithIntrinsicTypedFields As Boolean = False)
MyBase.New(info, region, suppressConstExpressionsSupport, trackUnassignments)
Me.initiallyAssignedVariables = initiallyAssignedVariables
Me._trackStructsWithIntrinsicTypedFields = trackStructsWithIntrinsicTypedFields
End Sub
Protected Overrides Sub InitForScan()
MyBase.InitForScan()
For Each parameter In MethodParameters
GetOrCreateSlot(parameter)
Next
Me._alreadyReported = BitVector.Empty ' no variables yet reported unassigned
Me.EnterParameters(MethodParameters) ' with parameters assigned
Dim methodMeParameter = Me.MeParameter ' and with 'Me' assigned as well
If methodMeParameter IsNot Nothing Then
Me.GetOrCreateSlot(methodMeParameter)
Me.EnterParameter(methodMeParameter)
End If
' Usually we need to treat locals used without being assigned first as assigned in the beginning of the block.
' When data flow analysis determines that the variable is sometimes used without being assigned first, we want
' to treat that variable, during region analysis, as assigned where it is introduced.
' However with goto statements that branch into for/foreach/using statements (error case) we need to treat them
' as assigned in the beginning of the method body.
'
' Example:
' Goto label1
' For x = 0 to 10
' label1:
' Dim y = [| x |] ' x should not be in dataFlowsOut.
' Next
'
' This can only happen in VB because the labels are visible in the whole method. In C# the labels are not visible
' this case.
'
If initiallyAssignedVariables IsNot Nothing Then
For Each local In initiallyAssignedVariables
SetSlotAssigned(GetOrCreateSlot(local))
Next
End If
End Sub
Protected Overrides Function Scan() As Boolean
If Not MyBase.Scan() Then
Return False
End If
' check unused variables
If Not _seenOnErrorOrResume Then
For Each local In _unusedVariables
ReportUnused(local)
Next
End If
' VB doesn't support "out" so it doesn't warn for unassigned parameters. However, check variables passed
' byref are assigned so that data flow analysis detects parameters flowing out.
If ShouldAnalyzeByRefParameters Then
LeaveParameters(MethodParameters)
End If
Dim methodMeParameter = Me.MeParameter ' and also 'Me'
If methodMeParameter IsNot Nothing Then
Me.LeaveParameter(methodMeParameter)
End If
Return True
End Function
Private Sub ReportUnused(local As LocalSymbol)
' Never report that the function value is unused
' Never report that local with empty name is unused
' Locals with empty name can be generated in code with syntax errors and
' we shouldn't report such locals as unused because they were not explicitly declared
' by the user in the code
If Not local.IsFunctionValue AndAlso Not String.IsNullOrEmpty(local.Name) Then
If _writtenVariables.Contains(local) Then
If local.IsConst Then
Me.diagnostics.Add(ERRID.WRN_UnusedLocalConst, local.Locations(0), If(local.Name, "dummy"))
End If
Else
Me.diagnostics.Add(ERRID.WRN_UnusedLocal, local.Locations(0), If(local.Name, "dummy"))
End If
End If
End Sub
Protected Overridable Sub ReportUnassignedByRefParameter(parameter As ParameterSymbol)
End Sub
''' <summary>
''' Perform data flow analysis, reporting all necessary diagnostics.
''' </summary>
Public Overloads Shared Sub Analyze(info As FlowAnalysisInfo, diagnostics As DiagnosticBag, suppressConstExpressionsSupport As Boolean)
Dim walker = New DataFlowPass(info, suppressConstExpressionsSupport)
If diagnostics IsNot Nothing Then
walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = True
End If
Try
Dim result As Boolean = walker.Analyze()
Debug.Assert(result)
If diagnostics IsNot Nothing Then
diagnostics.AddRange(walker.diagnostics)
End If
Catch ex As CancelledByStackGuardException When diagnostics IsNot Nothing
ex.AddAnError(diagnostics)
Finally
walker.Free()
End Try
End Sub
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
Return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException
End Function
Protected Overrides Sub Free()
Me._alreadyReported = BitVector.Null
MyBase.Free()
End Sub
Protected Overrides Function Dump(state As LocalState) As String
Dim builder As New StringBuilder()
builder.Append("[assigned ")
AppendBitNames(state.Assigned, builder)
builder.Append("]")
Return builder.ToString()
End Function
Protected Sub AppendBitNames(a As BitVector, builder As StringBuilder)
Dim any As Boolean = False
For Each bit In a.TrueBits
If any Then
builder.Append(", ")
End If
any = True
AppendBitName(bit, builder)
Next
End Sub
Protected Sub AppendBitName(bit As Integer, builder As StringBuilder)
Dim id As VariableIdentifier = variableBySlot(bit)
If id.ContainingSlot > 0 Then
AppendBitName(id.ContainingSlot, builder)
builder.Append(".")
End If
builder.Append(If(bit = 0, "*", id.Symbol.Name))
End Sub
#Region "Note Read/Write"
Protected Overridable Sub NoteRead(variable As Symbol)
If variable IsNot Nothing AndAlso variable.Kind = SymbolKind.Local Then
_unusedVariables.Remove(DirectCast(variable, LocalSymbol))
End If
End Sub
Protected Overridable Sub NoteWrite(variable As Symbol, value As BoundExpression)
If variable IsNot Nothing Then
_writtenVariables.Add(variable)
Dim local = TryCast(variable, LocalSymbol)
If value IsNot Nothing AndAlso (local IsNot Nothing AndAlso Not local.IsConst AndAlso local.Type.IsReferenceType OrElse value.HasErrors) Then
' We duplicate Dev10's behavior here. The reasoning is, I would guess, that otherwise unread
' variables of reference type are useful because they keep objects alive, i.e., they are read by the
' VM. And variables that are initialized by non-constant expressions presumably are useful because
' they enable us to clearly document a discarded return value from a method invocation, e.g. var
' discardedValue = F(); >shrug<
' Note, this rule only applies to local variables and not to const locals, i.e. we always report unused
' const locals. In addition, if the value has errors then suppress these diagnostics in all cases.
_unusedVariables.Remove(local)
End If
End If
End Sub
Protected Function GetNodeSymbol(node As BoundNode) As Symbol
While node IsNot Nothing
Select Case node.Kind
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If FieldAccessMayRequireTracking(fieldAccess) Then
node = fieldAccess.ReceiverOpt
Continue While
End If
Return Nothing
Case BoundKind.PropertyAccess
node = DirectCast(node, BoundPropertyAccess).ReceiverOpt
Continue While
Case BoundKind.MeReference
Return MeParameter
Case BoundKind.Local
Return DirectCast(node, BoundLocal).LocalSymbol
Case BoundKind.RangeVariable
Return DirectCast(node, BoundRangeVariable).RangeVariable
Case BoundKind.Parameter
Return DirectCast(node, BoundParameter).ParameterSymbol
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return GetNodeSymbol(substitute)
End If
Return Nothing
Case BoundKind.LocalDeclaration
Return DirectCast(node, BoundLocalDeclaration).LocalSymbol
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Return DirectCast(node, BoundForStatement).DeclaredOrInferredLocalOpt
Case BoundKind.ByRefArgumentWithCopyBack
node = DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument
Continue While
Case Else
Return Nothing
End Select
End While
Return Nothing
End Function
Protected Overridable Sub NoteWrite(node As BoundExpression, value As BoundExpression)
Dim symbol As Symbol = GetNodeSymbol(node)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteWrite(local, value)
Next
Else
NoteWrite(symbol, value)
End If
End If
End Sub
Protected Overridable Sub NoteRead(fieldAccess As BoundFieldAccess)
Dim symbol As Symbol = GetNodeSymbol(fieldAccess)
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Local AndAlso DirectCast(symbol, LocalSymbol).DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' We have several locals grouped in AmbiguousLocalsPseudoSymbol
For Each local In DirectCast(symbol, AmbiguousLocalsPseudoSymbol).Locals
NoteRead(local)
Next
Else
NoteRead(symbol)
End If
End If
End Sub
#End Region
#Region "Operations with slots"
''' <summary>
''' Locals are given slots when their declarations are encountered. We only need give slots to local variables, and
''' the "Me" variable of a structure constructs. Other variables are not given slots, and are therefore not tracked
''' by the analysis. This returns SlotKind.NotTracked for a variable that is not tracked, for fields of structs
''' that have the same assigned status as the container, and for structs that (recursively) contain no data members.
''' We do not need to track references to variables that occur before the variable is declared, as those are reported
''' in an earlier phase as "use before declaration". That allows us to avoid giving slots to local variables before
''' processing their declarations.
''' </summary>
Protected Function VariableSlot(symbol As Symbol, Optional containingSlot As Integer = 0) As Integer
containingSlot = DescendThroughTupleRestFields(symbol, containingSlot, forceContainingSlotsToExist:=False)
If symbol Is Nothing Then
' NOTE: This point may be hit in erroneous code, like
' referencing instance members from static methods
Return SlotKind.NotTracked
End If
Dim slot As Integer
Return If((_variableSlot.TryGetValue(New VariableIdentifier(symbol, containingSlot), slot)), slot, SlotKind.NotTracked)
End Function
''' <summary>
''' Return the slot for a variable, or SlotKind.NotTracked if it is not tracked (because, for example, it is an empty struct).
''' </summary>
Protected Function MakeSlotsForExpression(node As BoundExpression) As SlotCollection
Dim result As New SlotCollection() ' empty
Select Case node.Kind
Case BoundKind.MeReference, BoundKind.MyBaseReference, BoundKind.MyClassReference
If MeParameter IsNot Nothing Then
result.Append(GetOrCreateSlot(MeParameter))
End If
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
' multiple locals
For Each loc In DirectCast(local, AmbiguousLocalsPseudoSymbol).Locals
result.Append(GetOrCreateSlot(loc))
Next
Else
' just one simple local
result.Append(GetOrCreateSlot(local))
End If
Case BoundKind.RangeVariable
result.Append(GetOrCreateSlot(DirectCast(node, BoundRangeVariable).RangeVariable))
Case BoundKind.Parameter
result.Append(GetOrCreateSlot(DirectCast(node, BoundParameter).ParameterSymbol))
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
Dim fieldsymbol = fieldAccess.FieldSymbol
Dim receiverOpt = fieldAccess.ReceiverOpt
' do not track static fields
If fieldsymbol.IsShared OrElse receiverOpt Is Nothing OrElse receiverOpt.Kind = BoundKind.TypeExpression Then
Exit Select ' empty result
End If
' do not track fields of non-structs
If receiverOpt.Type Is Nothing OrElse receiverOpt.Type.TypeKind <> TypeKind.Structure Then
Exit Select ' empty result
End If
result = MakeSlotsForExpression(receiverOpt)
' update slots, reuse collection
' NOTE: we don't filter out SlotKind.NotTracked values
For i = 0 To result.Count - 1
result(i) = GetOrCreateSlot(fieldAccess.FieldSymbol, result(0))
Next
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return MakeSlotsForExpression(substitute)
End If
End Select
Return result
End Function
''' <summary>
''' Force a variable to have a slot.
''' </summary>
''' <param name = "symbol"></param>
''' <returns></returns>
Protected Function GetOrCreateSlot(symbol As Symbol, Optional containingSlot As Integer = 0) As Integer
containingSlot = DescendThroughTupleRestFields(symbol, containingSlot, forceContainingSlotsToExist:=True)
If containingSlot = SlotKind.NotTracked Then
Return SlotKind.NotTracked
End If
' Check if the slot already exists
Dim varIdentifier As New VariableIdentifier(symbol, containingSlot)
Dim slot As Integer
If Not _variableSlot.TryGetValue(varIdentifier, slot) Then
If symbol.Kind = SymbolKind.Local Then
Me._unusedVariables.Add(DirectCast(symbol, LocalSymbol))
End If
Dim variableType As TypeSymbol = GetVariableType(symbol)
If IsEmptyStructType(variableType) Then
Return SlotKind.NotTracked
End If
' Create a slot
slot = nextVariableSlot
nextVariableSlot = nextVariableSlot + 1
_variableSlot.Add(varIdentifier, slot)
If slot >= variableBySlot.Length Then
Array.Resize(Me.variableBySlot, slot * 2)
End If
variableBySlot(slot) = varIdentifier
End If
Me.Normalize(Me.State)
Return slot
End Function
''' <summary>
''' Descends through Rest fields of a tuple if "symbol" is an extended field
''' As a result the "symbol" will be adjusted to be the field of the innermost tuple
''' and a corresponding containingSlot is returned.
''' Return value -1 indicates a failure which could happen for the following reasons
''' a) Rest field does not exist, which could happen in rare error scenarios involving broken ValueTuple types
''' b) Rest is not tracked already and forceSlotsToExist is false (otherwise we create slots on demand)
''' </summary>
Private Function DescendThroughTupleRestFields(ByRef symbol As Symbol, containingSlot As Integer, forceContainingSlotsToExist As Boolean) As Integer
Dim fieldSymbol = TryCast(symbol, TupleFieldSymbol)
If fieldSymbol IsNot Nothing Then
Dim containingType As TypeSymbol = DirectCast(symbol.ContainingType, TupleTypeSymbol).UnderlyingNamedType
' for tuple fields the variable identifier represents the underlying field
symbol = fieldSymbol.TupleUnderlyingField
' descend through Rest fields
' force corresponding slots if do not exist
While Not TypeSymbol.Equals(containingType, symbol.ContainingType, TypeCompareKind.ConsiderEverything)
Dim restField = TryCast(containingType.GetMembers(TupleTypeSymbol.RestFieldName).FirstOrDefault(), FieldSymbol)
If restField Is Nothing Then
Return -1
End If
If forceContainingSlotsToExist Then
containingSlot = GetOrCreateSlot(restField, containingSlot)
Else
If Not _variableSlot.TryGetValue(New VariableIdentifier(restField, containingSlot), containingSlot) Then
Return -1
End If
End If
containingType = restField.Type.GetTupleUnderlyingTypeOrSelf()
End While
End If
Return containingSlot
End Function
' In C#, we moved this cache to a separate cache held onto by the compilation, so we didn't
' recompute it each time.
'
' This is not so simple in VB, because we'd have to move the cache for members of the
' struct, and we'd need two different caches depending on _trackStructsWithIntrinsicTypedFields.
' So this optimization is not done for now in VB.
Private ReadOnly _isEmptyStructType As New Dictionary(Of NamedTypeSymbol, Boolean)()
Protected Overridable Function IsEmptyStructType(type As TypeSymbol) As Boolean
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType Is Nothing Then
Return False
End If
If Not IsTrackableStructType(namedType) Then
Return False
End If
Dim result As Boolean = False
If _isEmptyStructType.TryGetValue(namedType, result) Then
Return result
End If
' to break cycles
_isEmptyStructType(namedType) = True
For Each field In GetStructInstanceFields(namedType)
If Not IsEmptyStructType(field.Type) Then
_isEmptyStructType(namedType) = False
Return False
End If
Next
_isEmptyStructType(namedType) = True
Return True
End Function
Private Shared Function IsTrackableStructType(symbol As TypeSymbol) As Boolean
If IsNonPrimitiveValueType(symbol) Then
Dim type = TryCast(symbol.OriginalDefinition, NamedTypeSymbol)
Return (type IsNot Nothing) AndAlso Not type.KnownCircularStruct
End If
Return False
End Function
''' <summary> Calculates the flag of being already reported; for structure types
''' the slot may be reported if ALL the children are reported </summary>
Private Function IsSlotAlreadyReported(symbolType As TypeSymbol, slot As Integer) As Boolean
If _alreadyReported(slot) Then
Return True
End If
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return False
End If
If Not IsTrackableStructType(symbolType) Then
Return False
End If
' For structures - check field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
If Not IsSlotAlreadyReported(field.Type, childSlot) Then
Return False
End If
Else
Return False ' slot not created yet
End If
Next
' Seems to be assigned through children
_alreadyReported(slot) = True
Return True
End Function
''' <summary> Marks slot as reported, propagates 'reported' flag to the children if necessary </summary>
Private Sub MarkSlotAsReported(symbolType As TypeSymbol, slot As Integer)
If _alreadyReported(slot) Then
Return
End If
_alreadyReported(slot) = True
' not applicable for 'special slots'
If slot <= SlotKind.FunctionValue Then
Return
End If
If Not IsTrackableStructType(symbolType) Then
Return
End If
' For structures - propagate to field slots
For Each field In GetStructInstanceFields(symbolType)
Dim childSlot = VariableSlot(field, slot)
If childSlot <> SlotKind.NotTracked Then
MarkSlotAsReported(field.Type, childSlot)
End If
Next
End Sub
''' <summary> Unassign a slot for a regular variable </summary>
Private Sub SetSlotUnassigned(slot As Integer)
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If Me._tryState.HasValue Then
Dim tryState = Me._tryState.Value
SetSlotUnassigned(slot, tryState)
Me._tryState = tryState
End If
SetSlotUnassigned(slot, Me.State)
End Sub
Private Sub SetSlotUnassigned(slot As Integer, ByRef state As LocalState)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
' If the state of the slot is 'assigned' we need to clear it
' and possibly propagate it to all the parents
state.Unassign(slot)
'unassign struct children (if possible)
If IsTrackableStructType(type) Then
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotUnassigned(childSlot, state)
End If
Next
End If
' propagate to parents
While id.ContainingSlot > 0
' check the parent
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
If Not state.IsAssigned(parentSlot) Then
Exit While
End If
' unassign and continue loop
state.Unassign(parentSlot)
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).IsFunctionValue Then
state.Unassign(SlotKind.FunctionValue)
End If
id = parentIdentifier
End While
End Sub
''' <summary>Assign a slot for a regular variable in a given state.</summary>
Private Sub SetSlotAssigned(slot As Integer, ByRef state As LocalState)
Dim id As VariableIdentifier = variableBySlot(slot)
Dim type As TypeSymbol = GetVariableType(id.Symbol)
Debug.Assert(Not IsEmptyStructType(type))
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If Not state.IsAssigned(slot) Then
' assign this slot
state.Assign(slot)
If IsTrackableStructType(type) Then
' propagate to children
For Each field In GetStructInstanceFields(type)
' get child's slot
' NOTE: we don't need to care about possible cycles here because we took care of it
' in MakeSlotImpl when we created slots; we will just get SlotKind.NotTracked in worst case
Dim childSlot = VariableSlot(field, slot)
If childSlot >= SlotKind.FirstAvailable Then
SetSlotAssigned(childSlot, state)
End If
Next
End If
' propagate to parents
While id.ContainingSlot > 0
' check if all parent's children are set
Dim parentSlot = id.ContainingSlot
Dim parentIdentifier = variableBySlot(parentSlot)
Dim parentSymbol As Symbol = parentIdentifier.Symbol
Dim parentStructType = GetVariableType(parentSymbol)
' exit while if there is at least one child with a slot which is not assigned
For Each childSymbol In GetStructInstanceFields(parentStructType)
Dim childSlot = GetOrCreateSlot(childSymbol, parentSlot)
If childSlot <> SlotKind.NotTracked AndAlso Not state.IsAssigned(childSlot) Then
Exit While
End If
Next
' otherwise the parent can be set to assigned
state.Assign(parentSlot)
If parentSymbol.Kind = SymbolKind.Local AndAlso DirectCast(parentSymbol, LocalSymbol).IsFunctionValue Then
state.Assign(SlotKind.FunctionValue)
End If
id = parentIdentifier
End While
End If
End Sub
''' <summary>Assign a slot for a regular variable.</summary>
Private Sub SetSlotAssigned(slot As Integer)
SetSlotAssigned(slot, Me.State)
End Sub
''' <summary> Hash structure fields as we may query them many times </summary>
Private _typeToMembersCache As Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol)) = Nothing
Private Function ShouldIgnoreStructField(field As FieldSymbol) As Boolean
If field.IsShared Then
Return True
End If
If Me._trackStructsWithIntrinsicTypedFields Then
' If the flag is set we do not ignore any structure instance fields
Return False
End If
Dim fieldType As TypeSymbol = field.Type
' otherwise of fields of intrinsic type are ignored
If fieldType.IsIntrinsicValueType() Then
Return True
End If
' it the type is a type parameter and also type does NOT guarantee it is
' always a reference type, we ignore the field following Dev11 implementation
If fieldType.IsTypeParameter() Then
Dim typeParam = DirectCast(fieldType, TypeParameterSymbol)
If Not typeParam.IsReferenceType Then
Return True
End If
End If
' We also do NOT ignore all non-private fields
If field.DeclaredAccessibility <> Accessibility.Private Then
Return False
End If
' Do NOT ignore private fields from source
' NOTE: We should do this for all fields, but dev11 ignores private fields from
' metadata, so we need to as well to avoid breaking people. That's why we're
' distinguishing between source and metadata, rather than between the current
' compilation and another compilation.
If field.Dangerous_IsFromSomeCompilationIncludingRetargeting Then
' NOTE: Dev11 ignores fields auto-generated for events
Dim eventOrProperty As Symbol = field.AssociatedSymbol
If eventOrProperty Is Nothing OrElse eventOrProperty.Kind <> SymbolKind.Event Then
Return False
End If
End If
'' If the field is private we don't ignore it if it is a field of a generic struct
If field.ContainingType.IsGenericType Then
Return False
End If
Return True
End Function
Private Function GetStructInstanceFields(type As TypeSymbol) As ImmutableArray(Of FieldSymbol)
Dim result As ImmutableArray(Of FieldSymbol) = Nothing
If _typeToMembersCache Is Nothing OrElse Not _typeToMembersCache.TryGetValue(type, result) Then
' load and add to cache
Dim builder = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each member In type.GetMembersUnordered()
' only fields
If member.Kind = SymbolKind.Field Then
Dim field = DirectCast(member, FieldSymbol)
' Do not report virtual tuple fields.
' They are additional aliases to the fields of the underlying struct or nested extensions.
' and as such are already accounted for via the nonvirtual fields.
If field.IsVirtualTupleField Then
Continue For
End If
' only instance fields
If Not ShouldIgnoreStructField(field) Then
' NOTE: DO NOT skip fields of intrinsic types if _trackStructsWithIntrinsicTypedFields is True
builder.Add(field)
End If
End If
Next
result = builder.ToImmutableAndFree()
If _typeToMembersCache Is Nothing Then
_typeToMembersCache = New Dictionary(Of TypeSymbol, ImmutableArray(Of FieldSymbol))
End If
_typeToMembersCache.Add(type, result)
End If
Return result
End Function
Private Shared Function GetVariableType(symbol As Symbol) As TypeSymbol
Select Case symbol.Kind
Case SymbolKind.Local
Return DirectCast(symbol, LocalSymbol).Type
Case SymbolKind.RangeVariable
Return DirectCast(symbol, RangeVariableSymbol).Type
Case SymbolKind.Field
Return DirectCast(symbol, FieldSymbol).Type
Case SymbolKind.Parameter
Return DirectCast(symbol, ParameterSymbol).Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End Function
Protected Sub SetSlotState(slot As Integer, assigned As Boolean)
Debug.Assert(slot <> SlotKind.Unreachable)
If slot = SlotKind.NotTracked Then
Return
ElseIf slot = SlotKind.FunctionValue Then
' Function value slot is treated in a special way. For example it does not have Symbol assigned
' Just do a simple assign/unassign
If assigned Then
Me.State.Assign(slot)
Else
Me.State.Unassign(slot)
End If
Else
' The rest should be a regular slot
If assigned Then
SetSlotAssigned(slot)
Else
SetSlotUnassigned(slot)
End If
End If
End Sub
#End Region
#Region "Assignments: Check and Report"
''' <summary>
''' Check that the given variable is definitely assigned. If not, produce an error.
''' </summary>
Protected Sub CheckAssigned(symbol As Symbol, node As SyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
If symbol IsNot Nothing Then
Dim local = TryCast(symbol, LocalSymbol)
If local IsNot Nothing AndAlso local.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals
Return
End If
' 'local' can be a pseudo-local representing a set of real locals
If local IsNot Nothing AndAlso local.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
Dim ambiguous = DirectCast(local, AmbiguousLocalsPseudoSymbol)
' Ambiguous implicit receiver is always considered to be assigned
VisitAmbiguousLocalSymbol(ambiguous)
' Note reads of locals
For Each subLocal In ambiguous.Locals
NoteRead(subLocal)
Next
Else
Dim slot As Integer = GetOrCreateSlot(symbol)
If slot >= Me.State.Assigned.Capacity Then
Normalize(Me.State)
End If
If slot >= SlotKind.FirstAvailable AndAlso Me.State.Reachable AndAlso Not Me.State.IsAssigned(slot) Then
ReportUnassigned(symbol, node, rwContext)
End If
NoteRead(symbol)
End If
End If
End Sub
''' <summary> Version of CheckAssigned for bound field access </summary>
Private Sub CheckAssigned(fieldAccess As BoundFieldAccess, node As SyntaxNode, Optional rwContext As ReadWriteContext = ReadWriteContext.None)
Dim unassignedSlot As Integer
If Me.State.Reachable AndAlso Not IsAssigned(fieldAccess, unassignedSlot) Then
ReportUnassigned(fieldAccess.FieldSymbol, node, rwContext, unassignedSlot, fieldAccess)
End If
NoteRead(fieldAccess)
End Sub
Protected Overridable Sub VisitAmbiguousLocalSymbol(ambiguous As AmbiguousLocalsPseudoSymbol)
End Sub
Protected Overrides Sub VisitLvalue(node As BoundExpression, Optional dontLeaveRegion As Boolean = False)
MyBase.VisitLvalue(node, True) ' Don't leave region
If node.Kind = BoundKind.Local Then
Dim symbol As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If symbol.DeclarationKind = LocalDeclarationKind.AmbiguousLocals Then
VisitAmbiguousLocalSymbol(DirectCast(symbol, AmbiguousLocalsPseudoSymbol))
End If
End If
' NOTE: we can skip checking if Me._firstInRegion is nothing because 'node' is not nothing
If Not dontLeaveRegion AndAlso node Is Me._lastInRegion AndAlso IsInside Then
Me.LeaveRegion()
End If
End Sub
''' <summary> Check node for being assigned, return the value of unassigned slot in unassignedSlot </summary>
Private Function IsAssigned(node As BoundExpression, ByRef unassignedSlot As Integer) As Boolean
unassignedSlot = SlotKind.NotTracked
If IsEmptyStructType(node.Type) Then
Return True
End If
Select Case node.Kind
Case BoundKind.MeReference
unassignedSlot = VariableSlot(MeParameter)
Case BoundKind.Local
Dim local As LocalSymbol = DirectCast(node, BoundLocal).LocalSymbol
If local.DeclarationKind <> LocalDeclarationKind.AmbiguousLocals Then
unassignedSlot = VariableSlot(local)
Else
' We never report ambiguous locals pseudo-symbol as unassigned,
unassignedSlot = SlotKind.NotTracked
VisitAmbiguousLocalSymbol(DirectCast(local, AmbiguousLocalsPseudoSymbol))
End If
Case BoundKind.RangeVariable
' range variables are always assigned
unassignedSlot = -1
Return True
Case BoundKind.Parameter
unassignedSlot = VariableSlot(DirectCast(node, BoundParameter).ParameterSymbol)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(node, BoundFieldAccess)
If Not FieldAccessMayRequireTracking(fieldAccess) OrElse IsAssigned(fieldAccess.ReceiverOpt, unassignedSlot) Then
Return True
End If
' NOTE: unassignedSlot must have been set by previous call to IsAssigned(...)
unassignedSlot = GetOrCreateSlot(fieldAccess.FieldSymbol, unassignedSlot)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Return IsAssigned(substitute, unassignedSlot)
End If
unassignedSlot = SlotKind.NotTracked
Case Else
' The value is a method call return value or something else we can assume is assigned.
unassignedSlot = SlotKind.NotTracked
End Select
Return Me.State.IsAssigned(unassignedSlot)
End Function
''' <summary>
''' Property controls Roslyn data flow analysis features which are disabled in command-line
''' compiler mode to maintain backward compatibility (mostly diagnostics not reported by Dev11),
''' but *enabled* in flow analysis API
''' </summary>
Protected Overridable ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Specifies if the analysis should process compiler generated locals.
'''
''' Note that data flow API should never report compiler generated variables
''' as well as those should not generate any diagnostics (like being unassigned, etc...).
'''
''' But when the analysis is used for iterators or async captures it should process
''' compiler generated locals as well...
''' </summary>
Protected Overridable ReadOnly Property ProcessCompilerGeneratedLocals As Boolean
Get
Return False
End Get
End Property
Private Function GetUnassignedSymbolFirstLocation(sym As Symbol, boundFieldAccess As BoundFieldAccess) As Location
Select Case sym.Kind
Case SymbolKind.Parameter
Return Nothing
Case SymbolKind.RangeVariable
Return Nothing
Case SymbolKind.Local
Dim locations As ImmutableArray(Of Location) = sym.Locations
Return If(locations.IsEmpty, Nothing, locations(0))
Case SymbolKind.Field
Debug.Assert(boundFieldAccess IsNot Nothing)
If sym.IsShared Then
Return Nothing
End If
Dim receiver As BoundExpression = boundFieldAccess.ReceiverOpt
Debug.Assert(receiver IsNot Nothing)
Select Case receiver.Kind
Case BoundKind.Local
Return GetUnassignedSymbolFirstLocation(DirectCast(receiver, BoundLocal).LocalSymbol, Nothing)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(receiver, BoundFieldAccess)
Return GetUnassignedSymbolFirstLocation(fieldAccess.FieldSymbol, fieldAccess)
Case Else
Return Nothing
End Select
Case Else
Debug.Assert(False, "Why is this reachable?")
Return Nothing
End Select
End Function
''' <summary>
''' Report a given variable as not definitely assigned. Once a variable has been so
''' reported, we suppress further reports of that variable.
''' </summary>
Protected Overridable Sub ReportUnassigned(sym As Symbol,
node As SyntaxNode,
rwContext As ReadWriteContext,
Optional slot As Integer = SlotKind.NotTracked,
Optional boundFieldAccess As BoundFieldAccess = Nothing)
If slot < SlotKind.FirstAvailable Then
slot = VariableSlot(sym)
End If
If slot >= Me._alreadyReported.Capacity Then
_alreadyReported.EnsureCapacity(Me.nextVariableSlot)
End If
If sym.Kind = SymbolKind.Parameter Then
' Because there are no Out parameters in VB, general workflow should not hit this point;
' but in region analysis parameters are being unassigned, so it is reachable
Return
End If
If sym.Kind = SymbolKind.RangeVariable Then
' Range variables are always assigned for the purpose of error reporting.
Return
End If
Debug.Assert(sym.Kind = SymbolKind.Local OrElse sym.Kind = SymbolKind.Field)
Dim localOrFieldType As TypeSymbol
Dim isFunctionValue As Boolean
Dim isStaticLocal As Boolean
Dim isImplicitlyDeclared As Boolean = False
If sym.Kind = SymbolKind.Local Then
Dim locSym = DirectCast(sym, LocalSymbol)
localOrFieldType = locSym.Type
isFunctionValue = locSym.IsFunctionValue AndAlso EnableBreakingFlowAnalysisFeatures
isStaticLocal = locSym.IsStatic
isImplicitlyDeclared = locSym.IsImplicitlyDeclared
Else
isFunctionValue = False
isStaticLocal = False
localOrFieldType = DirectCast(sym, FieldSymbol).Type
End If
If Not IsSlotAlreadyReported(localOrFieldType, slot) Then
Dim warning As ERRID = Nothing
' NOTE: When a variable is being used before declaration VB generates ERR_UseOfLocalBeforeDeclaration1
' NOTE: error, thus we don't want to generate redundant warning; we base such an analysis on node
' NOTE: and symbol locations
Dim firstLocation As Location = GetUnassignedSymbolFirstLocation(sym, boundFieldAccess)
If isImplicitlyDeclared OrElse firstLocation Is Nothing OrElse firstLocation.SourceSpan.Start < node.SpanStart Then
' Because VB does not support out parameters, only locals OR fields of local structures can be unassigned.
If localOrFieldType IsNot Nothing AndAlso Not isStaticLocal Then
If localOrFieldType.IsIntrinsicValueType OrElse localOrFieldType.IsReferenceType Then
If localOrFieldType.IsIntrinsicValueType AndAlso Not isFunctionValue Then
warning = Nothing
Else
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRef, ERRID.WRN_DefAsgUseNullRef)
End If
ElseIf localOrFieldType.IsValueType Then
' This is only reported for structures with reference type fields.
warning = If(rwContext = ReadWriteContext.ByRefArgument, ERRID.WRN_DefAsgUseNullRefByRefStr, ERRID.WRN_DefAsgUseNullRefStr)
Else
Debug.Assert(localOrFieldType.IsTypeParameter)
End If
If warning <> Nothing Then
Me.diagnostics.Add(warning, node.GetLocation(), If(sym.Name, "dummy"))
End If
End If
MarkSlotAsReported(localOrFieldType, slot)
End If
End If
End Sub
Private Sub CheckAssignedFunctionValue(local As LocalSymbol, node As SyntaxNode)
If Not Me.State.FunctionAssignedValue AndAlso Not _seenOnErrorOrResume Then
Dim type As TypeSymbol = local.Type
' NOTE: Dev11 does NOT report warning on user-defined empty value types
' Special case: We specifically want to give a warning if the user doesn't return from a WinRT AddHandler.
' NOTE: Strictly speaking, dev11 actually checks whether the return type is EventRegistrationToken (see IsWinRTEventAddHandler),
' but the conditions should be equivalent (i.e. return EventRegistrationToken if and only if WinRT).
If EnableBreakingFlowAnalysisFeatures OrElse Not type.IsValueType OrElse type.IsIntrinsicOrEnumType OrElse Not IsEmptyStructType(type) OrElse
(Me.MethodSymbol.MethodKind = MethodKind.EventAdd AndAlso DirectCast(Me.MethodSymbol.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent) Then
ReportUnassignedFunctionValue(local, node)
End If
End If
End Sub
Private Sub ReportUnassignedFunctionValue(local As LocalSymbol, node As SyntaxNode)
If Not _alreadyReported(SlotKind.FunctionValue) Then
Dim type As TypeSymbol = Nothing
Dim method = Me.MethodSymbol
type = method.ReturnType
If type IsNot Nothing AndAlso
Not (method.IsIterator OrElse
(method.IsAsync AndAlso type.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)))) Then
Dim warning As ERRID = Nothing
Dim localName As String = GetFunctionLocalName(method, local)
type = type.GetEnumUnderlyingTypeOrSelf
' Actual warning depends on whether the local is a function,
' property, or operator value versus reference type.
If type.IsIntrinsicValueType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpVal1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropVal1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncVal1
End Select
ElseIf type.IsReferenceType Then
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
warning = ERRID.WRN_DefAsgNoRetValOpRef1
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case Else
Debug.Assert(MethodSymbol.MethodKind = MethodKind.Ordinary OrElse MethodSymbol.MethodKind = MethodKind.LambdaMethod)
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
ElseIf type.TypeKind = TypeKind.TypeParameter Then
' IsReferenceType was false, so this type parameter was not known to be a reference type.
' Following past practice, no warning is given in this case.
Else
Debug.Assert(type.IsValueType)
Select Case MethodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' no warning is given in this case.
Case MethodKind.PropertyGet
warning = ERRID.WRN_DefAsgNoRetValPropRef1
Case MethodKind.EventAdd
' In Dev11, there wasn't time to change the syntax of AddHandler to allow the user
' to specify a return type (necessarily, EventRegistrationToken) for WinRT events.
' DevDiv #376690 reflects the fact that this leads to an incredibly confusing user
' experience if nothing is return: no diagnostics are reported, but RemoveHandler
' statements will silently fail. To prompt the user, (1) warn if there is no
' explicit return, and (2) modify the error message to say "AddHandler As
' EventRegistrationToken" to hint at the nature of the problem.
' Update: Dev11 just mangles an existing error message, but we'll introduce a new,
' clearer, one.
warning = ERRID.WRN_DefAsgNoRetValWinRtEventVal1
localName = MethodSymbol.AssociatedSymbol.Name
Case Else
warning = ERRID.WRN_DefAsgNoRetValFuncRef1
End Select
End If
If warning <> Nothing Then
Debug.Assert(localName IsNot Nothing)
Me.diagnostics.Add(warning, node.GetLocation(), localName)
End If
End If
_alreadyReported(SlotKind.FunctionValue) = True
End If
End Sub
Private Shared Function GetFunctionLocalName(method As MethodSymbol, local As LocalSymbol) As String
Select Case method.MethodKind
Case MethodKind.LambdaMethod
Return StringConstants.AnonymousMethodName
Case MethodKind.Conversion, MethodKind.UserDefinedOperator
' The operator's function local is op_<something> and not
' VB's operator name, so we need to take the identifier token
' directly
Dim operatorBlock = DirectCast(DirectCast(local.ContainingSymbol, SourceMemberMethodSymbol).BlockSyntax, OperatorBlockSyntax)
Return operatorBlock.OperatorStatement.OperatorToken.Text
Case Else
Return If(local.Name, method.Name)
End Select
End Function
''' <summary>
''' Mark a variable as assigned (or unassigned).
''' </summary>
Protected Overridable Sub Assign(node As BoundNode, value As BoundExpression, Optional assigned As Boolean = True)
Select Case node.Kind
Case BoundKind.LocalDeclaration
Dim local = DirectCast(node, BoundLocalDeclaration)
Debug.Assert(local.InitializerOpt Is value OrElse local.InitializedByAsNew)
Dim symbol = local.LocalSymbol
Dim slot As Integer = GetOrCreateSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
' Note write if the local has an initializer or if it is part of an as-new.
If assigned AndAlso (value IsNot Nothing OrElse local.InitializedByAsNew) Then NoteWrite(symbol, value)
Case BoundKind.ForToStatement,
BoundKind.ForEachStatement
Dim forStatement = DirectCast(node, BoundForStatement)
Dim symbol = forStatement.DeclaredOrInferredLocalOpt
Debug.Assert(symbol IsNot Nothing)
Dim slot As Integer = GetOrCreateSlot(symbol)
Dim written As Boolean = assigned OrElse Not Me.State.Reachable
SetSlotState(slot, written)
Case BoundKind.Local
Dim local = DirectCast(node, BoundLocal)
Dim symbol = local.LocalSymbol
If symbol.IsCompilerGenerated AndAlso Not Me.ProcessCompilerGeneratedLocals Then
' Do not process compiler generated temporary locals.
Return
End If
' Regular variable
Dim slot As Integer = GetOrCreateSlot(symbol)
SetSlotState(slot, assigned)
If symbol.IsFunctionValue Then
SetSlotState(SlotKind.FunctionValue, assigned)
End If
If assigned Then
NoteWrite(symbol, value)
End If
Case BoundKind.Parameter
Dim local = DirectCast(node, BoundParameter)
Dim symbol = local.ParameterSymbol
Dim slot As Integer = GetOrCreateSlot(symbol)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(symbol, value)
Case BoundKind.MeReference
' var local = node as BoundThisReference;
Dim slot As Integer = GetOrCreateSlot(MeParameter)
SetSlotState(slot, assigned)
If assigned Then NoteWrite(MeParameter, value)
Case BoundKind.FieldAccess, BoundKind.PropertyAccess
Dim expression = DirectCast(node, BoundExpression)
Dim slots As SlotCollection = MakeSlotsForExpression(expression)
For i = 0 To slots.Count - 1
SetSlotState(slots(i), assigned)
Next
slots.Free()
If assigned Then NoteWrite(expression, value)
Case BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder
Dim substitute As BoundExpression = Me.GetPlaceholderSubstitute(DirectCast(node, BoundValuePlaceholderBase))
If substitute IsNot Nothing Then
Assign(substitute, value, assigned)
End If
Case BoundKind.ByRefArgumentWithCopyBack
Assign(DirectCast(node, BoundByRefArgumentWithCopyBack).OriginalArgument, value, assigned)
Case Else
' Other kinds of left-hand-sides either represent things not tracked (e.g. array elements)
' or errors that have been reported earlier (e.g. assignment to a unary increment)
End Select
End Sub
#End Region
#Region "Try statements"
' When assignments happen inside a region, they are treated as UN-assignments.
' Generally this is enough.
'
' The tricky part is that any instruction in Try/Catch/Finally must be considered as potentially throwing.
' Even if a subsequent write outside of the region may kill an assignment inside the region, it cannot prevent escape of
' the previous assignment.
'
' === Example:
'
' Dim x as integer = 0
' Try
' [| region starts here
' x = 1
' Blah() ' <- this statement may throw. (any instruction can).
' |] region ends here
' x = 2 ' <- it may seem that this assignment kills one above, where in fact "x = 1" can easily escape.
' Finally
' SomeUse(x) ' we can see side effects of "x = 1" here
' End Try
'
' As a result, when dealing with exception handling flows we need to maintain a separate state
' that collects UN-assignments only and is not affected by subsequent assignments.
Private _tryState As OptionalState
Protected Overrides Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef _tryState As LocalState)
If Me.TrackUnassignments Then
' store original try state
Dim oldTryState As OptionalState = Me._tryState
' start with AllBitsSet (means there were no assignments)
Me._tryState = AllBitsSet()
' visit try block. Any assignment inside the region will UN-assign corresponding bit in the tryState.
MyBase.VisitTryBlock(tryBlock, node, _tryState)
' merge resulting tryState into tryState that we were given.
Me.IntersectWith(_tryState, Me._tryState.Value)
' restore and merge old state with new changes.
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
MyBase.VisitTryBlock(tryBlock, node, _tryState)
End If
End Sub
Protected Overrides Sub VisitCatchBlock(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As OptionalState = Me._tryState
Me._tryState = AllBitsSet()
Me.VisitCatchBlockInternal(catchBlock, finallyState)
Me.IntersectWith(finallyState, Me._tryState.Value)
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
Me.VisitCatchBlockInternal(catchBlock, finallyState)
End If
End Sub
Private Sub VisitCatchBlockInternal(catchBlock As BoundCatchBlock, ByRef finallyState As LocalState)
Dim local = catchBlock.LocalOpt
If local IsNot Nothing Then
GetOrCreateSlot(local)
End If
Dim exceptionSource = catchBlock.ExceptionSourceOpt
If exceptionSource IsNot Nothing Then
Assign(exceptionSource, value:=Nothing, assigned:=True)
End If
MyBase.VisitCatchBlock(catchBlock, finallyState)
End Sub
Protected Overrides Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef unsetInFinally As LocalState)
If Me.TrackUnassignments Then
Dim oldTryState As OptionalState = Me._tryState
Me._tryState = AllBitsSet()
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
Me.IntersectWith(unsetInFinally, Me._tryState.Value)
If oldTryState.HasValue Then
Dim tryState = Me._tryState.Value
Me.IntersectWith(tryState, oldTryState.Value)
Me._tryState = tryState
Else
Me._tryState = oldTryState
End If
Else
MyBase.VisitFinallyBlock(finallyBlock, unsetInFinally)
End If
End Sub
#End Region
Protected Overrides Function ReachableState() As LocalState
Return New LocalState(BitVector.Empty)
End Function
Private Sub EnterParameters(parameters As ImmutableArray(Of ParameterSymbol))
For Each parameter In parameters
EnterParameter(parameter)
Next
End Sub
Protected Overridable Sub EnterParameter(parameter As ParameterSymbol)
' this code has no effect except in the region analysis APIs, which assign
' variable slots to all parameters.
Dim slot As Integer = VariableSlot(parameter)
If slot >= SlotKind.FirstAvailable Then
Me.State.Assign(slot)
End If
NoteWrite(parameter, Nothing)
End Sub
Private Sub LeaveParameters(parameters As ImmutableArray(Of ParameterSymbol))
If Me.State.Reachable Then
For Each parameter In parameters
LeaveParameter(parameter)
Next
End If
End Sub
Private Sub LeaveParameter(parameter As ParameterSymbol)
If parameter.IsByRef Then
Dim slot = VariableSlot(parameter)
If Not Me.State.IsAssigned(slot) Then
ReportUnassignedByRefParameter(parameter)
End If
NoteRead(parameter)
End If
End Sub
Protected Overrides Function UnreachableState() As LocalState
' at this point we don't know what size of the bitarray to use, so we only set
' 'reachable' flag which mean 'all bits are set' in intersect/union
Return New LocalState(UnreachableBitsSet)
End Function
Protected Overrides Function AllBitsSet() As LocalState
Dim result = New LocalState(BitVector.AllSet(nextVariableSlot))
result.Unassign(SlotKind.Unreachable)
Return result
End Function
Protected Overrides Sub VisitLocalInReadWriteContext(node As BoundLocal, rwContext As ReadWriteContext)
MyBase.VisitLocalInReadWriteContext(node, rwContext)
CheckAssigned(node.LocalSymbol, node.Syntax, rwContext)
End Sub
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
CheckAssigned(node.LocalSymbol, node.Syntax, ReadWriteContext.None)
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
' Sometimes query expressions refer to query range variable just to
' copy its value to a new compound variable. There is no reference
' to the range variable in code and, from user point of view, there is
' no access to it.
If Not node.WasCompilerGenerated Then
CheckAssigned(node.RangeVariable, node.Syntax, ReadWriteContext.None)
End If
Return Nothing
End Function
' Should this local variable be considered assigned at first? It is if in the set of initially
' assigned variables, or else the current state is not reachable.
Protected Function ConsiderLocalInitiallyAssigned(variable As LocalSymbol) As Boolean
Return Not Me.State.Reachable OrElse
initiallyAssignedVariables IsNot Nothing AndAlso initiallyAssignedVariables.Contains(variable)
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned = DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax.Parent, node.InitializerOpt, placeholder)
Dim local As LocalSymbol = node.LocalSymbol
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
SetPlaceholderSubstitute(placeholder, New BoundLocal(node.Syntax, local, local.Type))
End If
' Create a slot for the declared variable to be able to track it.
Dim slot As Integer = GetOrCreateSlot(local)
'If initializer is a lambda, we need to treat the local as assigned within the lambda.
Assign(node, node.InitializerOpt,
ConsiderLocalInitiallyAssigned(local) OrElse
variableIsUsedDirectlyAndIsAlwaysAssigned OrElse
TreatTheLocalAsAssignedWithinTheLambda(local, node.InitializerOpt))
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
' Assign must be called after the initializer is analyzed, because the variable needs to be
' consider unassigned which the initializer is being analyzed.
MyBase.VisitLocalDeclaration(node)
End If
AssignLocalOnDeclaration(local, node)
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function TreatTheLocalAsAssignedWithinTheLambda(local As LocalSymbol, right As BoundExpression) As Boolean
Return IsConvertedLambda(right)
End Function
Private Shared Function IsConvertedLambda(value As BoundExpression) As Boolean
If value Is Nothing Then
Return False
End If
Do
Select Case value.Kind
Case BoundKind.Lambda
Return True
Case BoundKind.Conversion
value = DirectCast(value, BoundConversion).Operand
Case BoundKind.DirectCast
value = DirectCast(value, BoundDirectCast).Operand
Case BoundKind.TryCast
value = DirectCast(value, BoundTryCast).Operand
Case BoundKind.Parenthesized
value = DirectCast(value, BoundParenthesized).Expression
Case Else
Return False
End Select
Loop
End Function
Friend Overridable Sub AssignLocalOnDeclaration(local As LocalSymbol, node As BoundLocalDeclaration)
If node.InitializerOpt IsNot Nothing OrElse node.InitializedByAsNew Then
Assign(node, node.InitializerOpt)
End If
End Sub
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
' Implicitly declared local variables don't have LocalDeclarations nodes for them. Thus,
' we need to create slots for any implicitly declared local variables in this block.
' For flow analysis purposes, we treat an implicit declared local as equivalent to a variable declared at the
' start of the method body (this block) with no initializer.
Dim localVariables = node.Locals
For Each local In localVariables
If local.IsImplicitlyDeclared Then
SetSlotState(GetOrCreateSlot(local), ConsiderLocalInitiallyAssigned(local))
End If
Next
Return MyBase.VisitBlock(node)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Dim oldPending As SavedPending = SavePending()
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State
Me.SetState(If(finalState.Reachable, finalState.Clone(), Me.AllBitsSet()))
Me.State.Assigned(SlotKind.FunctionValue) = False
Dim save_alreadyReportedFunctionValue = _alreadyReported(SlotKind.FunctionValue)
_alreadyReported(SlotKind.FunctionValue) = False
EnterParameters(node.LambdaSymbol.Parameters)
VisitBlock(node.Body)
LeaveParameters(node.LambdaSymbol.Parameters)
Me.symbol = oldSymbol
_alreadyReported(SlotKind.FunctionValue) = save_alreadyReportedFunctionValue
Me.State.Assigned(SlotKind.FunctionValue) = True
RestorePending(oldPending)
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Dim oldSymbol = Me.symbol
Me.symbol = node.LambdaSymbol
Dim finalState As LocalState = Me.State.Clone()
VisitRvalue(node.Expression)
Me.symbol = oldSymbol
Me.IntersectWith(finalState, Me.State)
Me.SetState(finalState)
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
VisitRvalue(node.LastOperator)
Return Nothing
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
VisitRvalue(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
VisitRvalue(node.Source)
Return Nothing
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
VisitRvalue(node.ConversionCall)
Return Nothing
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
If node.CapturedGroupOpt IsNot Nothing Then
VisitRvalue(node.CapturedGroupOpt)
End If
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
VisitRvalue(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
VisitRvalue(node.Value)
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
If Not node.WasCompilerGenerated Then
CheckAssigned(node.ParameterSymbol, node.Syntax)
End If
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim result = MyBase.VisitFieldAccess(node)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, ReadWriteContext.None)
End If
Return result
End Function
Protected Overrides Sub VisitFieldAccessInReadWriteContext(node As BoundFieldAccess, rwContext As ReadWriteContext)
MyBase.VisitFieldAccessInReadWriteContext(node, rwContext)
If FieldAccessMayRequireTracking(node) Then
CheckAssigned(node, node.Syntax, rwContext)
End If
End Sub
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim left As BoundExpression = node.Left
'If right expression is a lambda, we need to treat the left side as assigned within the lambda.
Dim treatLocalAsAssigned As Boolean = False
If left.Kind = BoundKind.Local Then
treatLocalAsAssigned = TreatTheLocalAsAssignedWithinTheLambda(
DirectCast(left, BoundLocal).LocalSymbol, node.Right)
End If
If treatLocalAsAssigned Then
Assign(left, node.Right)
End If
MyBase.VisitAssignmentOperator(node)
If Not treatLocalAsAssigned Then
Assign(left, node.Right)
End If
Return Nothing
End Function
Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean
Get
Return True
End Get
End Property
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
MyBase.VisitRedimClause(node)
Assign(node.Operand, Nothing)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
MyBase.VisitReferenceAssignment(node)
Assign(node.ByRefLocal, node.LValue)
Return Nothing
End Function
Protected Overrides Sub VisitForControlInitialization(node As BoundForToStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, node.InitialValue)
End Sub
Protected Overrides Sub VisitForControlInitialization(node As BoundForEachStatement)
MyBase.VisitForControlInitialization(node)
Assign(node.ControlVariable, Nothing)
End Sub
Protected Overrides Sub VisitForStatementVariableDeclaration(node As BoundForStatement)
' if the for each statement declared a variable explicitly or by using local type inference we'll
' need to create a new slot for the new variable that is initially unassigned.
If node.DeclaredOrInferredLocalOpt IsNot Nothing Then
Dim slot As Integer = GetOrCreateSlot(node.DeclaredOrInferredLocalOpt) 'not initially assigned
Assign(node, Nothing, ConsiderLocalInitiallyAssigned(node.DeclaredOrInferredLocalOpt))
End If
End Sub
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
MyBase.VisitAnonymousTypeCreationExpression(node)
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Me.SetPlaceholderSubstitute(node.ExpressionPlaceholder, node.DraftPlaceholderSubstitute)
MyBase.VisitWithStatement(node)
Me.RemovePlaceholderSubstitute(node.ExpressionPlaceholder)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
If node.ResourceList.IsDefaultOrEmpty Then
' only an expression. Let the base class' implementation deal with digging into the expression
Return MyBase.VisitUsingStatement(node)
End If
' all locals are considered initially assigned, even if the initialization expression is missing in source (error case)
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
Dim local = variableDeclaration.LocalSymbol
Dim slot = GetOrCreateSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
Next
Else
Dim local = DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol
Dim slot = GetOrCreateSlot(local)
If slot >= 0 Then
SetSlotAssigned(slot)
NoteWrite(local, Nothing)
Else
Debug.Assert(IsEmptyStructType(local.Type))
End If
End If
Next
Dim result = MyBase.VisitUsingStatement(node)
' all locals are being read in the finally block.
For Each variableDeclarations In node.ResourceList
If variableDeclarations.Kind = BoundKind.AsNewLocalDeclarations Then
For Each variableDeclaration In DirectCast(variableDeclarations, BoundAsNewLocalDeclarations).LocalDeclarations
NoteRead(variableDeclaration.LocalSymbol)
Next
Else
NoteRead(DirectCast(variableDeclarations, BoundLocalDeclaration).LocalSymbol)
End If
Next
Return result
End Function
Protected Overridable ReadOnly Property IgnoreOutSemantics As Boolean
Get
Return True
End Get
End Property
Protected NotOverridable Overrides Sub VisitArgument(arg As BoundExpression, p As ParameterSymbol)
Debug.Assert(arg IsNot Nothing)
If p.IsByRef Then
If p.IsOut And Not Me.IgnoreOutSemantics Then
VisitLvalue(arg)
Else
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
End If
Else
VisitRvalue(arg)
End If
End Sub
Protected Overrides Sub WriteArgument(arg As BoundExpression, isOut As Boolean)
If Not isOut Then
CheckAssignedFromArgumentWrite(arg, arg.Syntax)
End If
Assign(arg, Nothing)
MyBase.WriteArgument(arg, isOut)
End Sub
Protected Sub CheckAssignedFromArgumentWrite(expr As BoundExpression, node As SyntaxNode)
If Not Me.State.Reachable Then
Return
End If
Select Case expr.Kind
Case BoundKind.Local
CheckAssigned(DirectCast(expr, BoundLocal).LocalSymbol, node)
Case BoundKind.Parameter
CheckAssigned(DirectCast(expr, BoundParameter).ParameterSymbol, node)
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(expr, BoundFieldAccess)
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If FieldAccessMayRequireTracking(fieldAccess) Then
CheckAssigned(fieldAccess, node, ReadWriteContext.ByRefArgument)
End If
Case BoundKind.EventAccess
Throw ExceptionUtilities.UnexpectedValue(expr.Kind) ' TODO: is this reachable at all?
Case BoundKind.MeReference,
BoundKind.MyClassReference,
BoundKind.MyBaseReference
CheckAssigned(MeParameter, node)
End Select
End Sub
Protected Overrides Sub VisitLateBoundArgument(arg As BoundExpression, isByRef As Boolean)
If isByRef Then
VisitRvalue(arg, rwContext:=ReadWriteContext.ByRefArgument)
Else
VisitRvalue(arg)
End If
End Sub
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
If Not node.IsEndOfMethodReturn Then
' We should mark it as set disregarding whether or not there is an expression; if there
' is no expression, error 30654 will be generated which in Dev10 suppresses this error
SetSlotState(SlotKind.FunctionValue, True)
Else
Dim functionLocal = TryCast(node.ExpressionOpt, BoundLocal)
If functionLocal IsNot Nothing Then
CheckAssignedFunctionValue(functionLocal.LocalSymbol, node.Syntax)
End If
End If
MyBase.VisitReturnStatement(node)
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
CheckAssigned(MeParameter, node.Syntax)
Return Nothing
End Function
''' <summary>
''' A variable declared with As New can be considered assigned before the initializer is executed in case the variable
''' is a value type. The reason is that in this case the initialization happens in place (not in a temporary) and
''' the variable already got the object creation expression assigned.
''' </summary>
Private Function DeclaredVariableIsAlwaysAssignedBeforeInitializer(syntax As SyntaxNode, boundInitializer As BoundExpression,
<Out> ByRef placeholder As BoundValuePlaceholderBase) As Boolean
placeholder = Nothing
If boundInitializer IsNot Nothing AndAlso
(boundInitializer.Kind = BoundKind.ObjectCreationExpression OrElse boundInitializer.Kind = BoundKind.NewT) Then
Dim boundInitializerBase = DirectCast(boundInitializer, BoundObjectCreationExpressionBase).InitializerOpt
If boundInitializerBase IsNot Nothing AndAlso boundInitializerBase.Kind = BoundKind.ObjectInitializerExpression Then
Dim objectInitializer = DirectCast(boundInitializerBase, BoundObjectInitializerExpression)
If syntax IsNot Nothing AndAlso syntax.Kind = SyntaxKind.VariableDeclarator Then
Dim declarator = DirectCast(syntax, VariableDeclaratorSyntax)
If declarator.AsClause IsNot Nothing AndAlso declarator.AsClause.Kind = SyntaxKind.AsNewClause Then
placeholder = objectInitializer.PlaceholderOpt
Return Not objectInitializer.CreateTemporaryLocalForInitialization
End If
End If
End If
End If
Return False
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Dim placeholder As BoundValuePlaceholderBase = Nothing
Dim variableIsUsedDirectlyAndIsAlwaysAssigned =
DeclaredVariableIsAlwaysAssignedBeforeInitializer(node.Syntax, node.Initializer, placeholder)
Dim declarations As ImmutableArray(Of BoundLocalDeclaration) = node.LocalDeclarations
If declarations.IsEmpty Then
Return Nothing
End If
' An initializer might access the declared variables in the initializer and therefore need to create a slot to
' track them
For Each localDeclaration In declarations
GetOrCreateSlot(localDeclaration.LocalSymbol)
Next
' NOTE: in case 'variableIsUsedDirectlyAndIsAlwaysAssigned' is set it must be
' Dim a[, b, ...] As New Struct(...) With { ... }.
'
' In this case Roslyn (following Dev10/Dev11) consecutively calls constructors
' and executes initializers for all declared variables. Thus, when the first
' initializer is being executed, all other locals are not assigned yet.
'
' This behavior is emulated below by assigning the first local and visiting
' the initializer before assigning all the other locals. We don't really need
' to revisit initializer after because all errors/warnings will be property
' reported in the first visit.
Dim localToUseAsSubstitute As LocalSymbol = CreateLocalSymbolForVariables(declarations)
' process the first local declaration once
Dim localDecl As BoundLocalDeclaration = declarations(0)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
' in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
' if needed, replace the placeholders with the bound local for the current declared variable.
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.SetPlaceholderSubstitute(placeholder, New BoundLocal(localDecl.Syntax, localToUseAsSubstitute, localToUseAsSubstitute.Type))
End If
VisitRvalue(node.Initializer)
Visit(localDecl) ' TODO: do we really need that?
' Visit all other declarations
For index = 1 To declarations.Length - 1
localDecl = declarations(index)
' A valuetype variable declared with AsNew and initialized by an object initializer is considered
' assigned when visiting the initializer, because the initialization happens inplace and the
' variable already got the object creation expression assigned (this assignment will be created
'in the local rewriter).
Assign(localDecl, node.Initializer, ConsiderLocalInitiallyAssigned(localDecl.LocalSymbol) OrElse variableIsUsedDirectlyAndIsAlwaysAssigned)
Visit(localDecl) ' TODO: do we really need that?
Next
' We also need to mark all
If variableIsUsedDirectlyAndIsAlwaysAssigned Then
Me.RemovePlaceholderSubstitute(placeholder)
End If
Return Nothing
End Function
Protected Overridable Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol
Debug.Assert(declarations.Length > 0)
Return declarations(0).LocalSymbol
End Function
Protected Overrides Sub VisitObjectCreationExpressionInitializer(node As BoundObjectInitializerExpressionBase)
Dim resetPlaceholder As Boolean = node IsNot Nothing AndAlso
node.Kind = BoundKind.ObjectInitializerExpression AndAlso
DirectCast(node, BoundObjectInitializerExpression).CreateTemporaryLocalForInitialization
If resetPlaceholder Then
Me.SetPlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt, Nothing) ' Override substitute
End If
MyBase.VisitObjectCreationExpressionInitializer(node)
If resetPlaceholder Then
Me.RemovePlaceholderSubstitute(DirectCast(node, BoundObjectInitializerExpression).PlaceholderOpt)
End If
End Sub
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
_seenOnErrorOrResume = True
Return MyBase.VisitOnErrorStatement(node)
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
_seenOnErrorOrResume = True
Return MyBase.VisitResumeStatement(node)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/Core/Def/ValueTracking/EmptyTreeViewItem.cs | // Licensed to the .NET Foundation under one or more 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.ValueTracking
{
internal class EmptyTreeViewItem : TreeViewItemBase
{
public static EmptyTreeViewItem Instance { get; } = new();
private EmptyTreeViewItem()
{
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ValueTracking
{
internal class EmptyTreeViewItem : TreeViewItemBase
{
public static EmptyTreeViewItem Instance { get; } = new();
private EmptyTreeViewItem()
{
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Test/Semantic/Semantics/NullableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class NullableSemanticTests : SemanticModelTestBase
{
[Fact, WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")]
public void NestedNullableWithAttemptedConversion()
{
var src =
@"using System;
class C {
public void Main()
{
Nullable<Nullable<int>> x = null;
Nullable<int> y = null;
Console.WriteLine(x == y);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,16): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
// Nullable<Nullable<int>> x = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Nullable<int>").WithArguments("System.Nullable<T>", "T", "int?"),
// (7,25): error CS0019: Operator '==' cannot be applied to operands of type 'int??' and 'int?'
// Console.WriteLine(x == y);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == y").WithArguments("==", "int??", "int?"));
}
[Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")]
public void TestBug12347()
{
string source = @"
using System;
class C
{
static void Main()
{
string? s1 = null;
Nullable<string> s2 = null;
Console.WriteLine(s1.ToString() + s2.ToString());
}
}";
var expected = new[]
{
// (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// string? s1 = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 11),
// (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (7,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// string? s1 = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 11),
// (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14));
}
[Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")]
public void TestBug12347_CSharp8()
{
string source = @"
using System;
class C
{
static void Main()
{
string? s1 = null;
Nullable<string> s2 = null;
Console.WriteLine(s1.ToString() + s2.ToString());
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (7,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// string? s1 = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 15),
// (8,18): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 18)
);
}
[Fact, WorkItem(529269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529269")]
public void TestLiftedIncrementOperatorBreakingChanges01()
{
// The native compiler not only *allows* this to compile, it lowers to:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1);
// c = temp2.HasValue ?
// C.op_Implicit_Nullable_Int_To_C(new short?((short)(temp2.GetValueOrDefault() + 1))) :
// null;
//
// !!!
//
// Not only does the native compiler silently insert a data-losing conversion from int to short,
// if the result of the initial conversion to int? is null, the result is a null *C*, not
// an implicit conversion from a null *int?* to C.
//
// This should simply be disallowed. The increment on int? produces int?, and there is no implicit
// conversion from int? to S.
string source1 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
public static implicit operator C(short? s) { return new C(s); }
static void Main()
{
C c = new C(null);
c++;
System.Console.WriteLine(object.ReferenceEquals(c, null));
}
}";
var comp = CreateCompilation(source1);
comp.VerifyDiagnostics(
// (11,5): error CS0266: Cannot implicitly convert type 'int?' to 'C'. An explicit conversion exists (are you missing a cast?)
// c++;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c++").WithArguments("int?", "C")
);
}
[Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")]
public void TestLiftedIncrementOperatorBreakingChanges02()
{
// Now here we have a case where the compilation *should* succeed, and does, but
// the native compiler and Roslyn produce opposite behavior. Again, the native
// compiler lowers this to:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1);
// c = temp2.HasValue ?
// C.op_Implicit_Nullable_Int_To_C(new int?(temp2.GetValueOrDefault() + 1)) :
// null;
//
// And therefore produces "True". The correct lowering, performed by Roslyn, is:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int( temp1 );
// int? temp3 = temp2.HasValue ?
// new int?(temp2.GetValueOrDefault() + 1)) :
// default(int?);
// c = C.op_Implicit_Nullable_Int_To_C(temp3);
//
// and therefore should produce "False".
string source2 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
public static implicit operator C(int? s) { return new C(s); }
static void Main()
{
C c = new C(null);
c++;
System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0);
}
}";
var verifier = CompileAndVerify(source: source2, expectedOutput: "0");
verifier = CompileAndVerify(source: source2, expectedOutput: "0");
// And in fact, this should work if there is an implicit conversion from the result of the addition
// to the type:
string source3 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
// There is an implicit conversion from int? to long? and therefore from int? to S.
public static implicit operator C(long? s) { return new C((int?)s); }
static void Main()
{
C c1 = new C(null);
c1++;
C c2 = new C(123);
c2++;
System.Console.WriteLine(!object.ReferenceEquals(c1, null) && c2.i.Value == 124 ? 1 : 0);
}
}";
verifier = CompileAndVerify(source: source3, expectedOutput: "1", verify: Verification.Fails);
verifier = CompileAndVerify(source: source3, expectedOutput: "1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
}
[Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")]
public void TestLiftedIncrementOperatorBreakingChanges03()
{
// Let's in fact verify that this works correctly for all possible conversions to built-in types:
string source4 = @"
using System;
class C
{
public readonly TYPE? i;
public C(TYPE? i) { this.i = i; }
public static implicit operator TYPE?(C c) { return c.i; }
public static implicit operator C(TYPE? s) { return new C(s); }
static void Main()
{
TYPE q = 10;
C x = new C(10);
T(1, x.i.Value == q);
T(2, (x++).i.Value == (q++));
T(3, x.i.Value == q);
T(4, (++x).i.Value == (++q));
T(5, x.i.Value == q);
T(6, (x--).i.Value == (q--));
T(7, x.i.Value == q);
T(8, (--x).i.Value == (--q));
T(9, x.i.Value == q);
C xn = new C(null);
F(11, xn.i.HasValue);
F(12, (xn++).i.HasValue);
F(13, xn.i.HasValue);
F(14, (++xn).i.HasValue);
F(15, xn.i.HasValue);
F(16, (xn--).i.HasValue);
F(17, xn.i.HasValue);
F(18, (--xn).i.HasValue);
F(19, xn.i.HasValue);
System.Console.WriteLine(0);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(""TYPE"" + line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(""TYPE"" + line.ToString());
}
}
";
foreach (string type in new[] { "int", "ushort", "byte", "long", "float", "decimal" })
{
CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", verify: Verification.Fails);
CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
}
}
[Fact]
public void TestLiftedBuiltInIncrementOperators()
{
string source = @"
using System;
class C
{
static void Main()
{
TYPE q = 10;
TYPE? x = 10;
T(1, x.Value == q);
T(2, (x++).Value == (q++));
T(3, x.Value == q);
T(4, (++x).Value == (++q));
T(5, x.Value == q);
T(6, (x--).Value == (q--));
T(7, x.Value == q);
T(8, (--x).Value == (--q));
T(9, x.Value == q);
int? xn = null;
F(11, xn.HasValue);
F(12, (xn++).HasValue);
F(13, xn.HasValue);
F(14, (++xn).HasValue);
F(15, xn.HasValue);
F(16, (xn--).HasValue);
F(17, xn.HasValue);
F(18, (--xn).HasValue);
F(19, xn.HasValue);
System.Console.WriteLine(0);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(""TYPE"" + line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(""TYPE"" + line.ToString());
}
}";
foreach (string type in new[] { "uint", "short", "sbyte", "ulong", "double", "decimal" })
{
string expected = "0";
var verifier = CompileAndVerify(source: source.Replace("TYPE", type), expectedOutput: expected);
}
}
[Fact]
public void TestLiftedUserDefinedIncrementOperators()
{
string source = @"
using System;
struct S
{
public int x;
public S(int x) { this.x = x; }
public static S operator ++(S s) { return new S(s.x + 1); }
public static S operator --(S s) { return new S(s.x - 1); }
}
class C
{
static void Main()
{
S? n = new S(1);
S s = new S(1);
T(1, n.Value.x == s.x);
T(2, (n++).Value.x == (s++).x);
T(3, n.Value.x == s.x);
T(4, (n--).Value.x == (s--).x);
T(5, n.Value.x == s.x);
T(6, (++n).Value.x == (++s).x);
T(7, n.Value.x == s.x);
T(8, (--n).Value.x == (--s).x);
T(9, n.Value.x == s.x);
n = null;
F(11, n.HasValue);
F(12, (n++).HasValue);
F(13, n.HasValue);
F(14, (n--).HasValue);
F(15, n.HasValue);
F(16, (++n).HasValue);
F(17, n.HasValue);
F(18, (--n).HasValue);
F(19, n.HasValue);
Console.WriteLine(1);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(line.ToString());
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "1");
}
[Fact]
public void TestNullableBuiltInUnaryOperator()
{
string source = @"
using System;
class C
{
static void Main()
{
Console.Write('!');
bool? bf = false;
bool? bt = true;
bool? bn = null;
Test((!bf).HasValue);
Test((!bf).Value);
Test((!bt).HasValue);
Test((!bt).Value);
Test((!bn).HasValue);
Console.WriteLine();
Console.Write('-');
int? i32 = -1;
int? i32n = null;
Test((-i32).HasValue);
Test((-i32) == 1);
Test((-i32) == -1);
Test((-i32n).HasValue);
Console.Write(1);
long? i64 = -1;
long? i64n = null;
Test((-i64).HasValue);
Test((-i64) == 1);
Test((-i64) == -1);
Test((-i64n).HasValue);
Console.Write(2);
float? r32 = -1.5f;
float? r32n = null;
Test((-r32).HasValue);
Test((-r32) == 1.5f);
Test((-r32) == -1.5f);
Test((-r32n).HasValue);
Console.Write(3);
double? r64 = -1.5;
double? r64n = null;
Test((-r64).HasValue);
Test((-r64) == 1.5);
Test((-r64) == -1.5);
Test((-r64n).HasValue);
Console.Write(4);
decimal? d = -1.5m;
decimal? dn = null;
Test((-d).HasValue);
Test((-d) == 1.5m);
Test((-d) == -1.5m);
Test((-dn).HasValue);
Console.WriteLine();
Console.Write('+');
Test((+i32).HasValue);
Test((+i32) == 1);
Test((+i32) == -1);
Test((+i32n).HasValue);
Console.Write(1);
uint? ui32 = 1;
uint? ui32n = null;
Test((+ui32).HasValue);
Test((+ui32) == 1);
Test((+ui32n).HasValue);
Console.Write(2);
Test((+i64).HasValue);
Test((+i64) == 1);
Test((+i64) == -1);
Test((+i64n).HasValue);
Console.Write(3);
ulong? ui64 = 1;
ulong? ui64n = null;
Test((+ui64).HasValue);
Test((+ui64) == 1);
Test((+ui64n).HasValue);
Console.Write(4);
Test((+r32).HasValue);
Test((+r32) == 1.5f);
Test((+r32) == -1.5f);
Test((+r32n).HasValue);
Console.Write(5);
Test((+r64).HasValue);
Test((+r64) == 1.5);
Test((+r64) == -1.5);
Test((+r64n).HasValue);
Console.Write(6);
Test((+d).HasValue);
Test((+d) == 1.5m);
Test((+d) == -1.5m);
Test((+dn).HasValue);
Console.WriteLine();
Console.Write('~');
i32 = 1;
Test((~i32).HasValue);
Test((~i32) == -2);
Test((~i32n).HasValue);
Console.Write(1);
Test((~ui32).HasValue);
Test((~ui32) == 0xFFFFFFFE);
Test((~ui32n).HasValue);
Console.Write(2);
i64 = 1;
Test((~i64).HasValue);
Test((~i64) == -2L);
Test((~i64n).HasValue);
Console.Write(3);
Test((~ui64).HasValue);
Test((~ui64) == 0xFFFFFFFFFFFFFFFE);
Test((~ui64n).HasValue);
Console.Write(4);
Base64FormattingOptions? e = Base64FormattingOptions.InsertLineBreaks;
Base64FormattingOptions? en = null;
Test((~e).HasValue);
Test((~e) == (Base64FormattingOptions)(-2));
Test((~en).HasValue);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}";
string expected =
@"!TTTFF
-TTFF1TTFF2TTFF3TTFF4TTFF
+TFTF1TTF2TFTF3TTF4TFTF5TFTF6TFTF
~TTF1TTF2TTF3TTF4TTF";
var verifier = CompileAndVerify(source: source, expectedOutput: expected);
}
[Fact]
public void TestNullableUserDefinedUnary()
{
string source = @"
using System;
struct S
{
public S(char c) { this.str = c.ToString(); }
public S(string str) { this.str = str; }
public string str;
public static S operator !(S s)
{
return new S('!' + s.str);
}
public static S operator ~(S s)
{
return new S('~' + s.str);
}
public static S operator -(S s)
{
return new S('-' + s.str);
}
public static S operator +(S s)
{
return new S('+' + s.str);
}
}
class C
{
static void Main()
{
S? s = new S('x');
S? sn = null;
Test((~s).HasValue);
Test((~sn).HasValue);
Console.WriteLine((~s).Value.str);
Test((!s).HasValue);
Test((!sn).HasValue);
Console.WriteLine((!s).Value.str);
Test((+s).HasValue);
Test((+sn).HasValue);
Console.WriteLine((+s).Value.str);
Test((-s).HasValue);
Test((-sn).HasValue);
Console.WriteLine((-s).Value.str);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}";
string expected =
@"TF~x
TF!x
TF+x
TF-x";
var verifier = CompileAndVerify(source: source, expectedOutput: expected);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7803")]
public void TestLiftedComparison()
{
TestNullableComparison("==", "FFTFF1FTFFTF2FFTFFT3TFFTFF4FTFFTF5FFTFFT",
"int", "short", "byte", "long", "double", "decimal", "char", "Base64FormattingOptions", "S", "bool");
TestNullableComparison("!=", "TTFTT1TFTTFT2TTFTTF3FTTFTT4TFTTFT5TTFTTF",
"uint", "ushort", "sbyte", "ulong", "float", "decimal", "char", "Base64FormattingOptions", "S", "bool");
TestNullableComparison("<", "FFFFF1FFTFFT2FFFFFF3FFFFFF4FFTFFT5FFFFFF",
"uint", "sbyte", "float", "decimal", "Base64FormattingOptions", "S");
TestNullableComparison("<=", "FFFFF1FTTFTT2FFTFFT3FFFFFF4FTTFTT5FFTFFT",
"int", "byte", "double", "decimal", "char");
TestNullableComparison(">", "FFFFF1FFFFFF2FTFFTF3FFFFFF4FFFFFF5FTFFTF",
"ushort", "ulong", "decimal");
TestNullableComparison(">=", "FFFFF1FTFFTF2FTTFTT3FFFFFF4FTFFTF5FTTFTT",
"short", "long", "decimal");
}
private void TestNullableComparison(
string oper,
string expected,
params string[] types)
{
string source = @"
using System;
struct S
{
public int i;
public S(int i) { this.i = i; }
public static bool operator ==(S x, S y) { return x.i == y.i; }
public static bool operator !=(S x, S y) { return x.i != y.i; }
public static bool operator <(S x, S y) { return x.i < y.i; }
public static bool operator <=(S x, S y) { return x.i <= y.i; }
public static bool operator >(S x, S y) { return x.i > y.i; }
public static bool operator >=(S x, S y) { return x.i >= y.i; }
}
class C
{
static void Main()
{
TYPE? xn0 = ZERO;
TYPE? xn1 = ONE;
TYPE? xnn = null;
TYPE x0 = ZERO;
TYPE x1 = ONE;
TYPE? yn0 = ZERO;
TYPE? yn1 = ONE;
TYPE? ynn = null;
TYPE y0 = ZERO;
TYPE y1 = ONE;
Test(null OP yn0);
Test(null OP yn1);
Test(null OP ynn);
Test(null OP y0);
Test(null OP y1);
Console.Write('1');
Test(xn0 OP null);
Test(xn0 OP yn0);
Test(xn0 OP yn1);
Test(xn0 OP ynn);
Test(xn0 OP y0);
Test(xn0 OP y1);
Console.Write('2');
Test(xn1 OP null);
Test(xn1 OP yn0);
Test(xn1 OP yn1);
Test(xn1 OP ynn);
Test(xn1 OP y0);
Test(xn1 OP y1);
Console.Write('3');
Test(xnn OP null);
Test(xnn OP yn0);
Test(xnn OP yn1);
Test(xnn OP ynn);
Test(xnn OP y0);
Test(xnn OP y1);
Console.Write('4');
Test(x0 OP null);
Test(x0 OP yn0);
Test(x0 OP yn1);
Test(x0 OP ynn);
Test(x0 OP y0);
Test(x0 OP y1);
Console.Write('5');
Test(x1 OP null);
Test(x1 OP yn0);
Test(x1 OP yn1);
Test(x1 OP ynn);
Test(x1 OP y0);
Test(x1 OP y1);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}
";
var zeros = new Dictionary<string, string>()
{
{ "int", "0" },
{ "uint", "0" },
{ "short", "0" },
{ "ushort", "0" },
{ "byte", "0" },
{ "sbyte", "0" },
{ "long", "0" },
{ "ulong", "0" },
{ "double", "0" },
{ "float", "0" },
{ "decimal", "0" },
{ "char", "'a'" },
{ "bool", "false" },
{ "Base64FormattingOptions", "Base64FormattingOptions.None" },
{ "S", "new S(0)" }
};
var ones = new Dictionary<string, string>()
{
{ "int", "1" },
{ "uint", "1" },
{ "short", "1" },
{ "ushort", "1" },
{ "byte", "1" },
{ "sbyte", "1" },
{ "long", "1" },
{ "ulong", "1" },
{ "double", "1" },
{ "float", "1" },
{ "decimal", "1" },
{ "char", "'b'" },
{ "bool", "true" },
{ "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" },
{ "S", "new S(1)" }
};
foreach (string t in types)
{
string s = source.Replace("TYPE", t).Replace("OP", oper).Replace("ZERO", zeros[t]).Replace("ONE", ones[t]);
var verifier = CompileAndVerify(source: s, expectedOutput: expected);
}
}
[Fact]
public void TestLiftedBuiltInBinaryArithmetic()
{
string[,] enumAddition =
{
//{ "sbyte", "Base64FormattingOptions"},
{ "byte", "Base64FormattingOptions"},
//{ "short", "Base64FormattingOptions"},
{ "ushort", "Base64FormattingOptions"},
//{ "int", "Base64FormattingOptions"},
//{ "uint", "Base64FormattingOptions"},
//{ "long", "Base64FormattingOptions"},
//{ "ulong", "Base64FormattingOptions"},
{ "char", "Base64FormattingOptions"},
//{ "decimal", "Base64FormattingOptions"},
//{ "double", "Base64FormattingOptions"},
//{ "float", "Base64FormattingOptions"},
{ "Base64FormattingOptions", "sbyte" },
{ "Base64FormattingOptions", "byte" },
{ "Base64FormattingOptions", "short" },
{ "Base64FormattingOptions", "ushort" },
{ "Base64FormattingOptions", "int" },
//{ "Base64FormattingOptions", "uint" },
//{ "Base64FormattingOptions", "long" },
//{ "Base64FormattingOptions", "ulong" },
{ "Base64FormattingOptions", "char" },
//{ "Base64FormattingOptions", "decimal" },
//{ "Base64FormattingOptions", "double" },
//{ "Base64FormattingOptions", "float" },
//{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
string[,] enumSubtraction =
{
{ "Base64FormattingOptions", "sbyte" },
//{ "Base64FormattingOptions", "byte" },
{ "Base64FormattingOptions", "short" },
{ "Base64FormattingOptions", "ushort" },
{ "Base64FormattingOptions", "int" },
//{ "Base64FormattingOptions", "uint" },
//{ "Base64FormattingOptions", "long" },
//{ "Base64FormattingOptions", "ulong" },
//{ "Base64FormattingOptions", "char" },
//{ "Base64FormattingOptions", "decimal" },
//{ "Base64FormattingOptions", "double" },
//{ "Base64FormattingOptions", "float" },
{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
string[,] numerics1 =
{
{ "sbyte", "sbyte" },
{ "sbyte", "byte" },
//{ "sbyte", "short" },
{ "sbyte", "ushort" },
//{ "sbyte", "int" },
{ "sbyte", "uint" },
//{ "sbyte", "long" },
//{ "sbyte", "ulong" },
//{ "sbyte", "char" },
{ "sbyte", "decimal" },
{ "sbyte", "double" },
//{ "sbyte", "float" },
//{ "byte", "sbyte" },
{ "byte", "byte" },
//{ "byte", "short" },
{ "byte", "ushort" },
//{ "byte", "int" },
{ "byte", "uint" },
//{ "byte", "long" },
{ "byte", "ulong" },
//{ "byte", "char" },
{ "byte", "decimal" },
//{ "byte", "double" },
{ "byte", "float" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
//{ "short", "ushort" },
{ "short", "int" },
//{ "short", "uint" },
{ "short", "long" },
//{ "short", "ulong" },
//{ "short", "char" },
{ "short", "decimal" },
//{ "short", "double" },
{ "short", "float" },
};
string[,] numerics2 =
{
//{ "ushort", "sbyte" },
//{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
//{ "ushort", "int" },
{ "ushort", "uint" },
{ "ushort", "long" },
//{ "ushort", "ulong" },
//{ "ushort", "char" },
//{ "ushort", "decimal" },
//{ "ushort", "double" },
{ "ushort", "float" },
{ "int", "sbyte" },
{ "int", "byte" },
//{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
//{ "int", "uint" },
{ "int", "long" },
// { "int", "ulong" },
{ "int", "char" },
//{ "int", "decimal" },
{ "int", "double" },
//{ "int", "float" },
//{ "uint", "sbyte" },
//{ "uint", "byte" },
{ "uint", "short" },
//{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "uint" },
{ "uint", "long" },
//{ "uint", "ulong" },
{ "uint", "char" },
//{ "uint", "decimal" },
//{ "uint", "double" },
{ "uint", "float" },
};
string[,] numerics3 =
{
{ "long", "sbyte" },
{ "long", "byte" },
//{ "long", "short" },
//{ "long", "ushort" },
//{ "long", "int" },
//{ "long", "uint" },
{ "long", "long" },
// { "long", "ulong" },
{ "long", "char" },
//{ "long", "decimal" },
//{ "long", "double" },
{ "long", "float" },
//{ "ulong", "sbyte" },
//{ "ulong", "byte" },
//{ "ulong", "short" },
{ "ulong", "ushort" },
//{ "ulong", "int" },
{ "ulong", "uint" },
//{ "ulong", "long" },
{ "ulong", "ulong" },
//{ "ulong", "char" },
{ "ulong", "decimal" },
{ "ulong", "double" },
//{ "ulong", "float" },
};
string[,] numerics4 =
{
{ "char", "sbyte" },
{ "char", "byte" },
{ "char", "short" },
{ "char", "ushort" },
//{ "char", "int" },
//{ "char", "uint" },
//{ "char", "long" },
{ "char", "ulong" },
{ "char", "char" },
//{ "char", "decimal" },
//{ "char", "double" },
{ "char", "float" },
//{ "decimal", "sbyte" },
//{ "decimal", "byte" },
//{ "decimal", "short" },
{ "decimal", "ushort" },
{ "decimal", "int" },
{ "decimal", "uint" },
{ "decimal", "long" },
//{ "decimal", "ulong" },
{ "decimal", "char" },
{ "decimal", "decimal" },
//{ "decimal", "double" },
//{ "decimal", "float" },
};
string[,] numerics5 =
{
//{ "double", "sbyte" },
{ "double", "byte" },
{ "double", "short" },
{ "double", "ushort" },
//{ "double", "int" },
{ "double", "uint" },
{ "double", "long" },
//{ "double", "ulong" },
{ "double", "char" },
//{ "double", "decimal" },
{ "double", "double" },
{ "double", "float" },
{ "float", "sbyte" },
//{ "float", "byte" },
//{ "float", "short" },
//{ "float", "ushort" },
{ "float", "int" },
//{ "float", "uint" },
//{ "float", "long" },
{ "float", "ulong" },
//{ "float", "char" },
//{ "float", "decimal" },
//{ "float", "double" },
{ "float", "float" },
};
string[,] shift1 =
{
{ "sbyte", "sbyte" },
{ "sbyte", "byte" },
{ "sbyte", "short" },
{ "sbyte", "ushort" },
{ "sbyte", "int" },
{ "sbyte", "char" },
{ "byte", "sbyte" },
{ "byte", "byte" },
{ "byte", "short" },
{ "byte", "ushort" },
{ "byte", "int" },
{ "byte", "char" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
{ "short", "ushort" },
{ "short", "int" },
{ "short", "char" },
{ "ushort", "sbyte" },
{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
{ "ushort", "int" },
{ "ushort", "char" },
};
string[,] shift2 =
{
{ "int", "sbyte" },
{ "int", "byte" },
{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
{ "int", "char" },
{ "uint", "sbyte" },
{ "uint", "byte" },
{ "uint", "short" },
{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "char" },
{ "long", "sbyte" },
{ "long", "byte" },
{ "long", "short" },
{ "long", "ushort" },
{ "long", "int" },
{ "long", "char" },
{ "ulong", "sbyte" },
{ "ulong", "byte" },
{ "ulong", "short" },
{ "ulong", "ushort" },
{ "ulong", "int" },
{ "ulong", "char" },
{ "char", "sbyte" },
{ "char", "byte" },
{ "char", "short" },
{ "char", "ushort" },
{ "char", "int" },
{ "char", "char" },
};
string[,] logical1 =
{
{ "sbyte", "sbyte" },
//{ "sbyte", "byte" },
{ "sbyte", "short" },
{ "sbyte", "ushort" },
{ "sbyte", "int" },
//{ "sbyte", "uint" },
{ "sbyte", "long" },
//{ "sbyte", "ulong" },
//{ "sbyte", "char" },
{ "byte", "sbyte" },
{ "byte", "byte" },
//{ "byte", "short" },
{ "byte", "ushort" },
//{ "byte", "int" },
{ "byte", "uint" },
//{ "byte", "long" },
//{ "byte", "ulong" },
{ "byte", "char" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
//{ "short", "ushort" },
{ "short", "int" },
//{ "short", "uint" },
{ "short", "long" },
//{ "short", "ulong" },
{ "short", "char" },
};
string[,] logical2 =
{
//{ "ushort", "sbyte" },
{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
//{ "ushort", "int" },
{ "ushort", "uint" },
//{ "ushort", "long" },
//{ "ushort", "ulong" },
//{ "ushort", "char" },
//{ "int", "sbyte" },
{ "int", "byte" },
//{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
//{ "int", "uint" },
{ "int", "long" },
//{ "int", "ulong" },
//{ "int", "char" },
{ "uint", "sbyte" },
//{ "uint", "byte" },
{ "uint", "short" },
//{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "uint" },
//{ "uint", "long" },
//{ "uint", "ulong" },
{ "uint", "char" },
};
string[,] logical3 =
{
//{ "long", "sbyte" },
{ "long", "byte" },
//{ "long", "short" },
{ "long", "ushort" },
//{ "long", "int" },
{ "long", "uint" },
{ "long", "long" },
// { "long", "ulong" },
{ "long", "char" },
//{ "ulong", "sbyte" },
{ "ulong", "byte" },
//{ "ulong", "short" },
{ "ulong", "ushort" },
//{ "ulong", "int" },
{ "ulong", "uint" },
//{ "ulong", "long" },
{ "ulong", "ulong" },
//{ "ulong", "char" },
{ "char", "sbyte" },
//{ "char", "byte" },
//{ "char", "short" },
{ "char", "ushort" },
{ "char", "int" },
//{ "char", "uint" },
//{ "char", "long" },
{ "char", "ulong" },
{ "char", "char" },
{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
// Use 2 instead of 0 so that we don't get divide by zero errors.
var twos = new Dictionary<string, string>()
{
{ "int", "2" },
{ "uint", "2" },
{ "short", "2" },
{ "ushort", "2" },
{ "byte", "2" },
{ "sbyte", "2" },
{ "long", "2" },
{ "ulong", "2" },
{ "double", "2" },
{ "float", "2" },
{ "decimal", "2" },
{ "char", "'\\u0002'" },
{ "Base64FormattingOptions", "Base64FormattingOptions.None" },
};
var ones = new Dictionary<string, string>()
{
{ "int", "1" },
{ "uint", "1" },
{ "short", "1" },
{ "ushort", "1" },
{ "byte", "1" },
{ "sbyte", "1" },
{ "long", "1" },
{ "ulong", "1" },
{ "double", "1" },
{ "float", "1" },
{ "decimal", "1" },
{ "char", "'\\u0001'" },
{ "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" },
};
var names = new Dictionary<string, string>()
{
{ "+", "plus" },
{ "-", "minus" },
{ "*", "times" },
{ "/", "divide" },
{ "%", "remainder" },
{ ">>", "rshift" },
{ "<<", "lshift" },
{ "&", "and" },
{ "|", "or" },
{ "^", "xor" }
};
var source = new StringBuilder(@"
using System;
class C
{
static void T(int x, bool b)
{
if (!b) throw new Exception(x.ToString());
}
static void F(int x, bool b)
{
if (b) throw new Exception(x.ToString());
}
");
string main = "static void Main() {";
string method = @"
static void METHOD_TYPEX_NAME_TYPEY()
{
TYPEX? xn0 = TWOX;
TYPEX? xn1 = ONEX;
TYPEX? xnn = null;
TYPEX x0 = TWOX;
TYPEX x1 = ONEX;
TYPEY? yn0 = TWOY;
TYPEY? yn1 = ONEY;
TYPEY? ynn = null;
TYPEY y0 = TWOY;
TYPEY y1 = ONEY;
F(1, (null OP yn0).HasValue);
F(2, (null OP yn1).HasValue);
F(3, (null OP ynn).HasValue);
F(4, (null OP y0).HasValue);
F(5, (null OP y1).HasValue);
F(6, (xn0 OP null).HasValue);
T(7, (xn0 OP yn0).Value == (x0 OP y0));
T(8, (xn0 OP yn1).Value == (x0 OP y1));
F(9, (xn0 OP ynn).HasValue);
T(10, (xn0 OP y0).Value == (x0 OP y0));
T(11, (xn0 OP y1).Value == (x0 OP y1));
F(12, (xn1 OP null).HasValue);
T(13, (xn1 OP yn0).Value == (x1 OP y0));
T(14, (xn1 OP yn1).Value == (x1 OP y1));
F(15, (xn1 OP ynn).HasValue);
T(16, (xn1 OP y0).Value == (x1 OP y0));
T(17, (xn1 OP y1).Value == (x1 OP y1));
F(18, (xnn OP null).HasValue);
F(19, (xnn OP yn0).HasValue);
F(20, (xnn OP yn1).HasValue);
F(21, (xnn OP ynn).HasValue);
F(22, (xnn OP y0).HasValue);
F(23, (xnn OP y1).HasValue);
F(24, (x0 OP null).HasValue);
T(25, (x0 OP yn0).Value == (x0 OP y0));
T(26, (x0 OP yn1).Value == (x0 OP y1));
F(27, (x0 OP ynn).HasValue);
F(28, (x1 OP null).HasValue);
T(29, (x1 OP yn0).Value == (x1 OP y0));
T(30, (x1 OP yn1).Value == (x1 OP y1));
F(31, (x1 OP ynn).HasValue);
}";
List<Tuple<string, string[,]>> items = new List<Tuple<string, string[,]>>()
{
Tuple.Create("*", numerics1),
Tuple.Create("/", numerics2),
Tuple.Create("%", numerics3),
Tuple.Create("+", numerics4),
Tuple.Create("+", enumAddition),
Tuple.Create("-", numerics5),
// UNDONE: Overload resolution of "enum - null" ,
// UNDONE: so this test is disabled:
// UNDONE: Tuple.Create("-", enumSubtraction),
Tuple.Create(">>", shift1),
Tuple.Create("<<", shift2),
Tuple.Create("&", logical1),
Tuple.Create("|", logical2),
Tuple.Create("^", logical3)
};
int m = 0;
foreach (var item in items)
{
string oper = item.Item1;
string[,] types = item.Item2;
for (int i = 0; i < types.GetLength(0); ++i)
{
++m;
string typeX = types[i, 0];
string typeY = types[i, 1];
source.Append(method
.Replace("METHOD", "M" + m)
.Replace("TYPEX", typeX)
.Replace("TYPEY", typeY)
.Replace("OP", oper)
.Replace("NAME", names[oper])
.Replace("TWOX", twos[typeX])
.Replace("ONEX", ones[typeX])
.Replace("TWOY", twos[typeY])
.Replace("ONEY", ones[typeY]));
main += "M" + m + "_" + typeX + "_" + names[oper] + "_" + typeY + "();\n";
}
}
source.Append(main);
source.Append("} }");
var verifier = CompileAndVerify(source: source.ToString(), expectedOutput: "");
}
[Fact]
public void TestLiftedUserDefinedBinaryArithmetic()
{
string source = @"
using System;
struct SX
{
public string str;
public SX(string str) { this.str = str; }
public SX(char c) { this.str = c.ToString(); }
public static SZ operator +(SX sx, SY sy) { return new SZ(sx.str + '+' + sy.str); }
public static SZ operator -(SX sx, SY sy) { return new SZ(sx.str + '-' + sy.str); }
public static SZ operator *(SX sx, SY sy) { return new SZ(sx.str + '*' + sy.str); }
public static SZ operator /(SX sx, SY sy) { return new SZ(sx.str + '/' + sy.str); }
public static SZ operator %(SX sx, SY sy) { return new SZ(sx.str + '%' + sy.str); }
public static SZ operator &(SX sx, SY sy) { return new SZ(sx.str + '&' + sy.str); }
public static SZ operator |(SX sx, SY sy) { return new SZ(sx.str + '|' + sy.str); }
public static SZ operator ^(SX sx, SY sy) { return new SZ(sx.str + '^' + sy.str); }
public static SZ operator >>(SX sx, int i) { return new SZ(sx.str + '>' + '>' + i.ToString()); }
public static SZ operator <<(SX sx, int i) { return new SZ(sx.str + '<' + '<' + i.ToString()); }
}
struct SY
{
public string str;
public SY(string str) { this.str = str; }
public SY(char c) { this.str = c.ToString(); }
}
struct SZ
{
public string str;
public SZ(string str) { this.str = str; }
public SZ(char c) { this.str = c.ToString(); }
public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; }
public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class C
{
static void T(bool b)
{
if (!b) throw new Exception();
}
static void F(bool b)
{
if (b) throw new Exception();
}
static void Main()
{
SX sx = new SX('a');
SX? sxn = sx;
SX? sxnn = null;
SY sy = new SY('b');
SY? syn = sy;
SY? synn = null;
int i1 = 1;
int? i1n = 1;
int? i1nn = null;
";
source += @"
T((sx + syn).Value == (sx + sy));
F((sx - synn).HasValue);
F((sx * null).HasValue);
T((sxn % sy).Value == (sx % sy));
T((sxn / syn).Value == (sx / sy));
F((sxn ^ synn).HasValue);
F((sxn & null).HasValue);
F((sxnn | sy).HasValue);
F((sxnn ^ syn).HasValue);
F((sxnn + synn).HasValue);
F((sxnn - null).HasValue);";
source += @"
T((sx << i1n).Value == (sx << i1));
F((sx >> i1nn).HasValue);
F((sx << null).HasValue);
T((sxn >> i1).Value == (sx >> i1));
T((sxn << i1n).Value == (sx << i1));
F((sxn >> i1nn).HasValue);
F((sxn << null).HasValue);
F((sxnn >> i1).HasValue);
F((sxnn << i1n).HasValue);
F((sxnn >> i1nn).HasValue);
F((sxnn << null).HasValue);";
source += "}}";
var verifier = CompileAndVerify(source: source, expectedOutput: "");
}
[Fact]
public void TestLiftedBoolLogicOperators()
{
string source = @"
using System;
class C
{
static void T(int x, bool? b) { if (!(b.HasValue && b.Value)) throw new Exception(x.ToString()); }
static void F(int x, bool? b) { if (!(b.HasValue && !b.Value)) throw new Exception(x.ToString()); }
static void N(int x, bool? b) { if (b.HasValue) throw new Exception(x.ToString()); }
static void Main()
{
bool bt = true;
bool bf = false;
bool? bnt = bt;
bool? bnf = bf;
bool? bnn = null;
T(1, true & bnt);
T(2, true & bnt);
F(3, true & bnf);
N(4, true & null);
N(5, true & bnn);
T(6, bt & bnt);
T(7, bt & bnt);
F(8, bt & bnf);
N(9, bt & null);
N(10, bt & bnn);
T(11, bnt & true);
T(12, bnt & bt);
T(13, bnt & bnt);
F(14, bnt & false);
F(15, bnt & bf);
F(16, bnt & bnf);
N(17, bnt & null);
N(18, bnt & bnn);
F(19, false & bnt);
F(20, false & bnf);
F(21, false & null);
F(22, false & bnn);
F(23, bf & bnt);
F(24, bf & bnf);
F(25, bf & null);
F(26, bf & bnn);
F(27, bnf & true);
F(28, bnf & bt);
F(29, bnf & bnt);
F(30, bnf & false);
F(31, bnf & bf);
F(32, bnf & bnf);
F(33, bnf & null);
F(34, bnf & bnn);
N(35, null & true);
N(36, null & bt);
N(37, null & bnt);
F(38, null & false);
F(39, null & bf);
F(40, null & bnf);
N(41, null & bnn);
N(42, bnn & true);
N(43, bnn & bt);
N(44, bnn & bnt);
F(45, bnn & false);
F(46, bnn & bf);
F(47, bnn & bnf);
N(48, bnn & null);
N(49, bnn & bnn);
T(51, true | bnt);
T(52, true | bnt);
T(53, true | bnf);
T(54, true | null);
T(55, true | bnn);
T(56, bt | bnt);
T(57, bt | bnt);
T(58, bt | bnf);
T(59, bt | null);
T(60, bt | bnn);
T(61, bnt | true);
T(62, bnt | bt);
T(63, bnt | bnt);
T(64, bnt | false);
T(65, bnt | bf);
T(66, bnt | bnf);
T(67, bnt | null);
T(68, bnt | bnn);
T(69, false | bnt);
F(70, false | bnf);
N(71, false | null);
N(72, false | bnn);
T(73, bf | bnt);
F(74, bf | bnf);
N(75, bf | null);
N(76, bf | bnn);
T(77, bnf | true);
T(78, bnf | bt);
T(79, bnf | bnt);
F(80, bnf | false);
F(81, bnf | bf);
F(82, bnf | bnf);
N(83, bnf | null);
N(84, bnf | bnn);
T(85, null | true);
T(86, null | bt);
T(87, null | bnt);
N(88, null | false);
N(89, null | bf);
N(90, null | bnf);
N(91, null | bnn);
T(92, bnn | true);
T(93, bnn | bt);
T(94, bnn | bnt);
N(95, bnn | false);
N(96, bnn | bf);
N(97, bnn | bnf);
N(98, bnn | null);
N(99, bnn | bnn);
F(101, true ^ bnt);
F(102, true ^ bnt);
T(103, true ^ bnf);
N(104, true ^ null);
N(105, true ^ bnn);
F(106, bt ^ bnt);
F(107, bt ^ bnt);
T(108, bt ^ bnf);
N(109, bt ^ null);
N(110, bt ^ bnn);
F(111, bnt ^ true);
F(112, bnt ^ bt);
F(113, bnt ^ bnt);
T(114, bnt ^ false);
T(115, bnt ^ bf);
T(116, bnt ^ bnf);
N(117, bnt ^ null);
N(118, bnt ^ bnn);
T(119, false ^ bnt);
F(120, false ^ bnf);
N(121, false ^ null);
N(122, false ^ bnn);
T(123, bf ^ bnt);
F(124, bf ^ bnf);
N(125, bf ^ null);
N(126, bf ^ bnn);
T(127, bnf ^ true);
T(128, bnf ^ bt);
T(129, bnf ^ bnt);
F(130, bnf ^ false);
F(131, bnf ^ bf);
F(132, bnf ^ bnf);
N(133, bnf ^ null);
N(134, bnf ^ bnn);
N(135, null ^ true);
N(136, null ^ bt);
N(137, null ^ bnt);
N(138, null ^ false);
N(139, null ^ bf);
N(140, null ^ bnf);
N(141, null ^ bnn);
N(142, bnn ^ true);
N(143, bnn ^ bt);
N(144, bnn ^ bnt);
N(145, bnn ^ false);
N(146, bnn ^ bf);
N(147, bnn ^ bnf);
N(148, bnn ^ null);
N(149, bnn ^ bnn);
}
}";
var verifier = CompileAndVerify(source: source, expectedOutput: "");
}
[Fact]
public void TestLiftedCompoundAssignment()
{
string source = @"
using System;
class C
{
static void Main()
{
int? n = 1;
int a = 2;
int? b = 3;
short c = 4;
short? d = 5;
int? e = null;
n += a;
T(1, n == 3);
n += b;
T(2, n == 6);
n += c;
T(3, n == 10);
n += d;
T(4, n == 15);
n += e;
F(5, n.HasValue);
n += a;
F(6, n.HasValue);
n += b;
F(7, n.HasValue);
n += c;
F(8, n.HasValue);
n += d;
F(9, n.HasValue);
Console.WriteLine(123);
}
static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); }
static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); }
}";
var verifier = CompileAndVerify(source: source, expectedOutput: "123");
}
#region "Regression"
[Fact, WorkItem(543837, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543837")]
public void Test11827()
{
string source2 = @"
using System;
class Program
{
static void Main()
{
Func<decimal?, decimal?> lambda = a => { return checked(a * a); };
Console.WriteLine(0);
}
}";
var verifier = CompileAndVerify(source: source2, expectedOutput: "0");
}
[Fact, WorkItem(544001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544001")]
public void NullableUsedInUsingStatement()
{
string source = @"
using System;
struct S : IDisposable
{
public void Dispose()
{
Console.WriteLine(123);
}
static void Main()
{
using (S? r = new S())
{
Console.Write(r);
}
}
}
";
CompileAndVerify(source: source, expectedOutput: @"S123");
}
[Fact, WorkItem(544002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544002")]
public void NullableUserDefinedUnary02()
{
string source = @"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator +(S? s) { return s.HasValue ? 10 : -10; }
public static int operator -(S s) { return 2; }
public static int operator -(S? s) { return s.HasValue ? 20 : -20; }
public static int operator !(S s) { return 3; }
public static int operator !(S? s) { return s.HasValue ? 30 : -30; }
public static int operator ~(S s) { return 4; }
public static int operator ~(S? s) { return s.HasValue ? 40 : -40; }
public static void Main()
{
S? sq = new S();
Console.Write(+sq);
Console.Write(-sq);
Console.Write(!sq);
Console.Write(~sq);
sq = null;
Console.Write(+sq);
Console.Write(-sq);
Console.Write(!sq);
Console.Write(~sq);
}
}
";
CompileAndVerify(source: source, expectedOutput: @"10203040-10-20-30-40");
}
[Fact, WorkItem(544005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544005")]
public void NoNullableValueFromOptionalParam()
{
string source = @"
class Test
{
static void M(
double? d0 = null,
double? d1 = 1.11,
double? d2 = 2,
double? d3 = default(double?),
double d4 = 4,
double d5 = default(double),
string s6 = ""6"",
string s7 = null,
string s8 = default(string))
{
System.Console.WriteLine(""0:{0} 1:{1} 2:{2} 3:{3} 4:{4} 5:{5} 6:{6} 7:{7} 8:{8}"",
d0, d1.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d2, d3, d4, d5, s6, s7, s8);
}
static void Main()
{
M();
}
}
";
string expected = @"0: 1:1.11 2:2 3: 4:4 5:0 6:6 7: 8:";
var verifier = CompileAndVerify(source, expectedOutput: expected);
}
[Fact, WorkItem(544006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544006")]
public void ConflictImportedMethodWithNullableOptionalParam()
{
string source = @"
public class Parent
{
public int Goo(int? d = 0) { return (int)d; }
}
";
string source2 = @"
public class Parent
{
public int Goo(int? d = 0) { return (int)d; }
}
public class Test
{
public static void Main()
{
Parent p = new Parent();
System.Console.Write(p.Goo(0));
}
}
";
var complib = CreateCompilation(
source,
options: TestOptions.ReleaseDll,
assemblyName: "TestDLL");
var comp = CreateCompilation(
source2,
references: new MetadataReference[] { complib.EmitToImageReference() },
options: TestOptions.ReleaseExe,
assemblyName: "TestEXE");
comp.VerifyDiagnostics(
// (11,9): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''.
// Parent p = new Parent();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent"),
// (11,24): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''.
// Parent p = new Parent();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent")
);
CompileAndVerify(comp, expectedOutput: @"0");
}
[Fact, WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")]
public void BindDelegateToObjectMethods()
{
string source = @"
using System;
public class Test
{
delegate int I();
static void Main()
{
int? x = 123;
Func<string> d1 = x.ToString;
I d2 = x.GetHashCode;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(544909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544909")]
public void OperationOnEnumNullable()
{
string source = @"
using System;
public class NullableTest
{
public enum E : short { Zero = 0, One = 1, Max = System.Int16.MaxValue, Min = System.Int16.MinValue }
static E? NULL = null;
public static void Main()
{
E? nub = 0;
Test(nub.HasValue); // t
nub = NULL;
Test(nub.HasValue); // f
nub = ~nub;
Test(nub.HasValue); // f
nub = NULL++;
Test(nub.HasValue); // f
nub = 0;
nub++;
Test(nub.HasValue); // t
Test(nub.GetValueOrDefault() == E.One); // t
nub = E.Max;
nub++;
Test(nub.GetValueOrDefault() == E.Min); // t
}
static void Test(bool b)
{
Console.Write(b ? 't' : 'f');
}
}
";
CompileAndVerify(source, expectedOutput: "tfffttt");
}
[Fact, WorkItem(544583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544583")]
public void ShortCircuitOperatorsOnNullable()
{
string source = @"
class A
{
static void Main()
{
bool? b1 = true, b2 = false;
var bb = b1 && b2;
bb = b1 || b2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,18): error CS0019: Operator '&&' cannot be applied to operands of type 'bool?' and 'bool?'
// var bb = b1 && b2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 && b2").WithArguments("&&", "bool?", "bool?"),
// (8,14): error CS0019: Operator '||' cannot be applied to operands of type 'bool?' and 'bool?'
// bb = b1 || b2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 || b2").WithArguments("||", "bool?", "bool?")
);
}
[Fact]
public void ShortCircuitLiftedUserDefinedOperators()
{
// This test illustrates a bug in the native compiler which Roslyn fixes.
// The native compiler disallows a *lifted* & operator from being used as an &&
// operator, but allows a *nullable* & operator to be used as an && operator.
// There is no good reason for this discrepancy; either both should be legal
// (because we can obviously generate good code that does what the user wants)
// or we should disallow both.
string source = @"
using System;
struct C
{
public bool b;
public C(bool b) { this.b = b; }
public static C operator &(C c1, C c2) { return new C(c1.b & c2.b); }
public static C operator |(C c1, C c2) { return new C(c1.b | c2.b); }
// null is false
public static bool operator true(C? c) { return c == null ? false : c.Value.b; }
public static bool operator false(C? c) { return c == null ? true : !c.Value.b; }
public static C? True() { Console.Write('t'); return new C(true); }
public static C? False() { Console.Write('f'); return new C(false); }
public static C? Null() { Console.Write('n'); return new C?(); }
}
struct D
{
public bool b;
public D(bool b) { this.b = b; }
public static D? operator &(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b & d2.Value.b)) : (D?)null; }
public static D? operator |(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b | d2.Value.b)) : (D?)null; }
// null is false
public static bool operator true(D? d) { return d == null ? false : d.Value.b; }
public static bool operator false(D? d) { return d == null ? true : !d.Value.b; }
public static D? True() { Console.Write('t'); return new D(true); }
public static D? False() { Console.Write('f'); return new D(false); }
public static D? Null() { Console.Write('n'); return new D?(); }
}
class P
{
static void Main()
{
D?[] results1 =
{
D.True() && D.True(), // tt --> t
D.True() && D.False(), // tf --> f
D.True() && D.Null(), // tn --> n
D.False() && D.True(), // f --> f
D.False() && D.False(), // f --> f
D.False() && D.Null(), // f --> f
D.Null() && D.True(), // n --> n
D.Null() && D.False(), // n --> n
D.Null() && D.Null() // n --> n
};
Console.WriteLine();
foreach(D? r in results1)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
C?[] results2 =
{
C.True() && C.True(),
C.True() && C.False(),
C.True() && C.Null(),
C.False() && C.True(),
C.False() && C.False(),
C.False() && C.Null(),
C.Null() && C.True(),
C.Null() && C.False(),
C.Null() && C.Null()
};
Console.WriteLine();
foreach(C? r in results2)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
D?[] results3 =
{
D.True() || D.True(), // t --> t
D.True() || D.False(), // t --> t
D.True() || D.Null(), // t --> t
D.False() || D.True(), // ft --> t
D.False() || D.False(), // ff --> f
D.False() || D.Null(), // fn --> n
D.Null() || D.True(), // nt --> n
D.Null() || D.False(), // nf --> n
D.Null() || D.Null() // nn --> n
};
Console.WriteLine();
foreach(D? r in results3)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
C?[] results4 =
{
C.True() || C.True(),
C.True() || C.False(),
C.True() || C.Null(),
C.False() || C.True(),
C.False() || C.False(),
C.False() || C.Null(),
C.Null() || C.True(),
C.Null() || C.False(),
C.Null() || C.Null()
};
Console.WriteLine();
foreach(C? r in results4)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
}
}
";
string expected = @"tttftnfffnnn
tfnfffnnn
tttftnfffnnn
tfnfffnnn
tttftfffnntnfnn
ttttfnnnn
tttftfffnntnfnn
ttttfnnnn";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact, WorkItem(529530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529530"), WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void NullableEnumMinusNull()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Console.WriteLine((xn0 - null).HasValue);
}
}";
CompileAndVerify(source, expectedOutput: "False").VerifyDiagnostics(
// (9,28): warning CS0458: The result of the expression is always 'null' of type 'int?'
// Console.WriteLine((xn0 - null).HasValue);
Diagnostic(ErrorCode.WRN_AlwaysNull, "xn0 - null").WithArguments("int?").WithLocation(9, 28)
);
}
[Fact]
public void NullableNullEquality()
{
var source = @"
using System;
public struct S
{
public static void Main()
{
S? s = new S();
Console.WriteLine(null == s);
}
}";
CompileAndVerify(source, expectedOutput: "False");
}
[Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")]
public void Op_ExplicitImplicitOnNullable()
{
var source = @"
using System;
class Test
{
static void Main()
{
var x = (int?).op_Explicit(1);
var y = (Nullable<int>).op_Implicit(2);
}
}
";
// VB now allow these syntax, but C# does NOT (spec said)
// Dev11 & Roslyn: (8,23): error CS1525: Invalid expression term '.'
// ---
// Dev11: error CS0118: 'int?' is a 'type' but is used like a 'variable'
// Roslyn: (9,18): error CS0119: 'int?' is a type, which is not valid in the given context
// Roslyn: (9,33): error CS0571: 'int?.implicit operator int?(int)': cannot explicitly call operator or accessor
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments("."),
Diagnostic(ErrorCode.ERR_BadSKunknown, "Nullable<int>").WithArguments("int?", "type"),
Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Implicit").WithArguments("int?.implicit operator int?(int)")
);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class NullableSemanticTests : SemanticModelTestBase
{
[Fact, WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")]
public void NestedNullableWithAttemptedConversion()
{
var src =
@"using System;
class C {
public void Main()
{
Nullable<Nullable<int>> x = null;
Nullable<int> y = null;
Console.WriteLine(x == y);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,16): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
// Nullable<Nullable<int>> x = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Nullable<int>").WithArguments("System.Nullable<T>", "T", "int?"),
// (7,25): error CS0019: Operator '==' cannot be applied to operands of type 'int??' and 'int?'
// Console.WriteLine(x == y);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == y").WithArguments("==", "int??", "int?"));
}
[Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")]
public void TestBug12347()
{
string source = @"
using System;
class C
{
static void Main()
{
string? s1 = null;
Nullable<string> s2 = null;
Console.WriteLine(s1.ToString() + s2.ToString());
}
}";
var expected = new[]
{
// (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
// string? s1 = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 11),
// (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (7,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// string? s1 = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 11),
// (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14));
}
[Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")]
public void TestBug12347_CSharp8()
{
string source = @"
using System;
class C
{
static void Main()
{
string? s1 = null;
Nullable<string> s2 = null;
Console.WriteLine(s1.ToString() + s2.ToString());
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (7,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context.
// string? s1 = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 15),
// (8,18): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// Nullable<string> s2 = null;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 18)
);
}
[Fact, WorkItem(529269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529269")]
public void TestLiftedIncrementOperatorBreakingChanges01()
{
// The native compiler not only *allows* this to compile, it lowers to:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1);
// c = temp2.HasValue ?
// C.op_Implicit_Nullable_Int_To_C(new short?((short)(temp2.GetValueOrDefault() + 1))) :
// null;
//
// !!!
//
// Not only does the native compiler silently insert a data-losing conversion from int to short,
// if the result of the initial conversion to int? is null, the result is a null *C*, not
// an implicit conversion from a null *int?* to C.
//
// This should simply be disallowed. The increment on int? produces int?, and there is no implicit
// conversion from int? to S.
string source1 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
public static implicit operator C(short? s) { return new C(s); }
static void Main()
{
C c = new C(null);
c++;
System.Console.WriteLine(object.ReferenceEquals(c, null));
}
}";
var comp = CreateCompilation(source1);
comp.VerifyDiagnostics(
// (11,5): error CS0266: Cannot implicitly convert type 'int?' to 'C'. An explicit conversion exists (are you missing a cast?)
// c++;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c++").WithArguments("int?", "C")
);
}
[Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")]
public void TestLiftedIncrementOperatorBreakingChanges02()
{
// Now here we have a case where the compilation *should* succeed, and does, but
// the native compiler and Roslyn produce opposite behavior. Again, the native
// compiler lowers this to:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1);
// c = temp2.HasValue ?
// C.op_Implicit_Nullable_Int_To_C(new int?(temp2.GetValueOrDefault() + 1)) :
// null;
//
// And therefore produces "True". The correct lowering, performed by Roslyn, is:
//
// C temp1 = c;
// int? temp2 = C.op_Implicit_C_To_Nullable_Int( temp1 );
// int? temp3 = temp2.HasValue ?
// new int?(temp2.GetValueOrDefault() + 1)) :
// default(int?);
// c = C.op_Implicit_Nullable_Int_To_C(temp3);
//
// and therefore should produce "False".
string source2 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
public static implicit operator C(int? s) { return new C(s); }
static void Main()
{
C c = new C(null);
c++;
System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0);
}
}";
var verifier = CompileAndVerify(source: source2, expectedOutput: "0");
verifier = CompileAndVerify(source: source2, expectedOutput: "0");
// And in fact, this should work if there is an implicit conversion from the result of the addition
// to the type:
string source3 = @"
class C
{
public readonly int? i;
public C(int? i) { this.i = i; }
public static implicit operator int?(C c) { return c.i; }
// There is an implicit conversion from int? to long? and therefore from int? to S.
public static implicit operator C(long? s) { return new C((int?)s); }
static void Main()
{
C c1 = new C(null);
c1++;
C c2 = new C(123);
c2++;
System.Console.WriteLine(!object.ReferenceEquals(c1, null) && c2.i.Value == 124 ? 1 : 0);
}
}";
verifier = CompileAndVerify(source: source3, expectedOutput: "1", verify: Verification.Fails);
verifier = CompileAndVerify(source: source3, expectedOutput: "1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
}
[Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")]
public void TestLiftedIncrementOperatorBreakingChanges03()
{
// Let's in fact verify that this works correctly for all possible conversions to built-in types:
string source4 = @"
using System;
class C
{
public readonly TYPE? i;
public C(TYPE? i) { this.i = i; }
public static implicit operator TYPE?(C c) { return c.i; }
public static implicit operator C(TYPE? s) { return new C(s); }
static void Main()
{
TYPE q = 10;
C x = new C(10);
T(1, x.i.Value == q);
T(2, (x++).i.Value == (q++));
T(3, x.i.Value == q);
T(4, (++x).i.Value == (++q));
T(5, x.i.Value == q);
T(6, (x--).i.Value == (q--));
T(7, x.i.Value == q);
T(8, (--x).i.Value == (--q));
T(9, x.i.Value == q);
C xn = new C(null);
F(11, xn.i.HasValue);
F(12, (xn++).i.HasValue);
F(13, xn.i.HasValue);
F(14, (++xn).i.HasValue);
F(15, xn.i.HasValue);
F(16, (xn--).i.HasValue);
F(17, xn.i.HasValue);
F(18, (--xn).i.HasValue);
F(19, xn.i.HasValue);
System.Console.WriteLine(0);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(""TYPE"" + line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(""TYPE"" + line.ToString());
}
}
";
foreach (string type in new[] { "int", "ushort", "byte", "long", "float", "decimal" })
{
CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", verify: Verification.Fails);
CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
}
}
[Fact]
public void TestLiftedBuiltInIncrementOperators()
{
string source = @"
using System;
class C
{
static void Main()
{
TYPE q = 10;
TYPE? x = 10;
T(1, x.Value == q);
T(2, (x++).Value == (q++));
T(3, x.Value == q);
T(4, (++x).Value == (++q));
T(5, x.Value == q);
T(6, (x--).Value == (q--));
T(7, x.Value == q);
T(8, (--x).Value == (--q));
T(9, x.Value == q);
int? xn = null;
F(11, xn.HasValue);
F(12, (xn++).HasValue);
F(13, xn.HasValue);
F(14, (++xn).HasValue);
F(15, xn.HasValue);
F(16, (xn--).HasValue);
F(17, xn.HasValue);
F(18, (--xn).HasValue);
F(19, xn.HasValue);
System.Console.WriteLine(0);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(""TYPE"" + line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(""TYPE"" + line.ToString());
}
}";
foreach (string type in new[] { "uint", "short", "sbyte", "ulong", "double", "decimal" })
{
string expected = "0";
var verifier = CompileAndVerify(source: source.Replace("TYPE", type), expectedOutput: expected);
}
}
[Fact]
public void TestLiftedUserDefinedIncrementOperators()
{
string source = @"
using System;
struct S
{
public int x;
public S(int x) { this.x = x; }
public static S operator ++(S s) { return new S(s.x + 1); }
public static S operator --(S s) { return new S(s.x - 1); }
}
class C
{
static void Main()
{
S? n = new S(1);
S s = new S(1);
T(1, n.Value.x == s.x);
T(2, (n++).Value.x == (s++).x);
T(3, n.Value.x == s.x);
T(4, (n--).Value.x == (s--).x);
T(5, n.Value.x == s.x);
T(6, (++n).Value.x == (++s).x);
T(7, n.Value.x == s.x);
T(8, (--n).Value.x == (--s).x);
T(9, n.Value.x == s.x);
n = null;
F(11, n.HasValue);
F(12, (n++).HasValue);
F(13, n.HasValue);
F(14, (n--).HasValue);
F(15, n.HasValue);
F(16, (++n).HasValue);
F(17, n.HasValue);
F(18, (--n).HasValue);
F(19, n.HasValue);
Console.WriteLine(1);
}
static void T(int line, bool b)
{
if (!b) throw new Exception(line.ToString());
}
static void F(int line, bool b)
{
if (b) throw new Exception(line.ToString());
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "1");
}
[Fact]
public void TestNullableBuiltInUnaryOperator()
{
string source = @"
using System;
class C
{
static void Main()
{
Console.Write('!');
bool? bf = false;
bool? bt = true;
bool? bn = null;
Test((!bf).HasValue);
Test((!bf).Value);
Test((!bt).HasValue);
Test((!bt).Value);
Test((!bn).HasValue);
Console.WriteLine();
Console.Write('-');
int? i32 = -1;
int? i32n = null;
Test((-i32).HasValue);
Test((-i32) == 1);
Test((-i32) == -1);
Test((-i32n).HasValue);
Console.Write(1);
long? i64 = -1;
long? i64n = null;
Test((-i64).HasValue);
Test((-i64) == 1);
Test((-i64) == -1);
Test((-i64n).HasValue);
Console.Write(2);
float? r32 = -1.5f;
float? r32n = null;
Test((-r32).HasValue);
Test((-r32) == 1.5f);
Test((-r32) == -1.5f);
Test((-r32n).HasValue);
Console.Write(3);
double? r64 = -1.5;
double? r64n = null;
Test((-r64).HasValue);
Test((-r64) == 1.5);
Test((-r64) == -1.5);
Test((-r64n).HasValue);
Console.Write(4);
decimal? d = -1.5m;
decimal? dn = null;
Test((-d).HasValue);
Test((-d) == 1.5m);
Test((-d) == -1.5m);
Test((-dn).HasValue);
Console.WriteLine();
Console.Write('+');
Test((+i32).HasValue);
Test((+i32) == 1);
Test((+i32) == -1);
Test((+i32n).HasValue);
Console.Write(1);
uint? ui32 = 1;
uint? ui32n = null;
Test((+ui32).HasValue);
Test((+ui32) == 1);
Test((+ui32n).HasValue);
Console.Write(2);
Test((+i64).HasValue);
Test((+i64) == 1);
Test((+i64) == -1);
Test((+i64n).HasValue);
Console.Write(3);
ulong? ui64 = 1;
ulong? ui64n = null;
Test((+ui64).HasValue);
Test((+ui64) == 1);
Test((+ui64n).HasValue);
Console.Write(4);
Test((+r32).HasValue);
Test((+r32) == 1.5f);
Test((+r32) == -1.5f);
Test((+r32n).HasValue);
Console.Write(5);
Test((+r64).HasValue);
Test((+r64) == 1.5);
Test((+r64) == -1.5);
Test((+r64n).HasValue);
Console.Write(6);
Test((+d).HasValue);
Test((+d) == 1.5m);
Test((+d) == -1.5m);
Test((+dn).HasValue);
Console.WriteLine();
Console.Write('~');
i32 = 1;
Test((~i32).HasValue);
Test((~i32) == -2);
Test((~i32n).HasValue);
Console.Write(1);
Test((~ui32).HasValue);
Test((~ui32) == 0xFFFFFFFE);
Test((~ui32n).HasValue);
Console.Write(2);
i64 = 1;
Test((~i64).HasValue);
Test((~i64) == -2L);
Test((~i64n).HasValue);
Console.Write(3);
Test((~ui64).HasValue);
Test((~ui64) == 0xFFFFFFFFFFFFFFFE);
Test((~ui64n).HasValue);
Console.Write(4);
Base64FormattingOptions? e = Base64FormattingOptions.InsertLineBreaks;
Base64FormattingOptions? en = null;
Test((~e).HasValue);
Test((~e) == (Base64FormattingOptions)(-2));
Test((~en).HasValue);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}";
string expected =
@"!TTTFF
-TTFF1TTFF2TTFF3TTFF4TTFF
+TFTF1TTF2TFTF3TTF4TFTF5TFTF6TFTF
~TTF1TTF2TTF3TTF4TTF";
var verifier = CompileAndVerify(source: source, expectedOutput: expected);
}
[Fact]
public void TestNullableUserDefinedUnary()
{
string source = @"
using System;
struct S
{
public S(char c) { this.str = c.ToString(); }
public S(string str) { this.str = str; }
public string str;
public static S operator !(S s)
{
return new S('!' + s.str);
}
public static S operator ~(S s)
{
return new S('~' + s.str);
}
public static S operator -(S s)
{
return new S('-' + s.str);
}
public static S operator +(S s)
{
return new S('+' + s.str);
}
}
class C
{
static void Main()
{
S? s = new S('x');
S? sn = null;
Test((~s).HasValue);
Test((~sn).HasValue);
Console.WriteLine((~s).Value.str);
Test((!s).HasValue);
Test((!sn).HasValue);
Console.WriteLine((!s).Value.str);
Test((+s).HasValue);
Test((+sn).HasValue);
Console.WriteLine((+s).Value.str);
Test((-s).HasValue);
Test((-sn).HasValue);
Console.WriteLine((-s).Value.str);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}";
string expected =
@"TF~x
TF!x
TF+x
TF-x";
var verifier = CompileAndVerify(source: source, expectedOutput: expected);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7803")]
public void TestLiftedComparison()
{
TestNullableComparison("==", "FFTFF1FTFFTF2FFTFFT3TFFTFF4FTFFTF5FFTFFT",
"int", "short", "byte", "long", "double", "decimal", "char", "Base64FormattingOptions", "S", "bool");
TestNullableComparison("!=", "TTFTT1TFTTFT2TTFTTF3FTTFTT4TFTTFT5TTFTTF",
"uint", "ushort", "sbyte", "ulong", "float", "decimal", "char", "Base64FormattingOptions", "S", "bool");
TestNullableComparison("<", "FFFFF1FFTFFT2FFFFFF3FFFFFF4FFTFFT5FFFFFF",
"uint", "sbyte", "float", "decimal", "Base64FormattingOptions", "S");
TestNullableComparison("<=", "FFFFF1FTTFTT2FFTFFT3FFFFFF4FTTFTT5FFTFFT",
"int", "byte", "double", "decimal", "char");
TestNullableComparison(">", "FFFFF1FFFFFF2FTFFTF3FFFFFF4FFFFFF5FTFFTF",
"ushort", "ulong", "decimal");
TestNullableComparison(">=", "FFFFF1FTFFTF2FTTFTT3FFFFFF4FTFFTF5FTTFTT",
"short", "long", "decimal");
}
private void TestNullableComparison(
string oper,
string expected,
params string[] types)
{
string source = @"
using System;
struct S
{
public int i;
public S(int i) { this.i = i; }
public static bool operator ==(S x, S y) { return x.i == y.i; }
public static bool operator !=(S x, S y) { return x.i != y.i; }
public static bool operator <(S x, S y) { return x.i < y.i; }
public static bool operator <=(S x, S y) { return x.i <= y.i; }
public static bool operator >(S x, S y) { return x.i > y.i; }
public static bool operator >=(S x, S y) { return x.i >= y.i; }
}
class C
{
static void Main()
{
TYPE? xn0 = ZERO;
TYPE? xn1 = ONE;
TYPE? xnn = null;
TYPE x0 = ZERO;
TYPE x1 = ONE;
TYPE? yn0 = ZERO;
TYPE? yn1 = ONE;
TYPE? ynn = null;
TYPE y0 = ZERO;
TYPE y1 = ONE;
Test(null OP yn0);
Test(null OP yn1);
Test(null OP ynn);
Test(null OP y0);
Test(null OP y1);
Console.Write('1');
Test(xn0 OP null);
Test(xn0 OP yn0);
Test(xn0 OP yn1);
Test(xn0 OP ynn);
Test(xn0 OP y0);
Test(xn0 OP y1);
Console.Write('2');
Test(xn1 OP null);
Test(xn1 OP yn0);
Test(xn1 OP yn1);
Test(xn1 OP ynn);
Test(xn1 OP y0);
Test(xn1 OP y1);
Console.Write('3');
Test(xnn OP null);
Test(xnn OP yn0);
Test(xnn OP yn1);
Test(xnn OP ynn);
Test(xnn OP y0);
Test(xnn OP y1);
Console.Write('4');
Test(x0 OP null);
Test(x0 OP yn0);
Test(x0 OP yn1);
Test(x0 OP ynn);
Test(x0 OP y0);
Test(x0 OP y1);
Console.Write('5');
Test(x1 OP null);
Test(x1 OP yn0);
Test(x1 OP yn1);
Test(x1 OP ynn);
Test(x1 OP y0);
Test(x1 OP y1);
}
static void Test(bool b)
{
Console.Write(b ? 'T' : 'F');
}
}
";
var zeros = new Dictionary<string, string>()
{
{ "int", "0" },
{ "uint", "0" },
{ "short", "0" },
{ "ushort", "0" },
{ "byte", "0" },
{ "sbyte", "0" },
{ "long", "0" },
{ "ulong", "0" },
{ "double", "0" },
{ "float", "0" },
{ "decimal", "0" },
{ "char", "'a'" },
{ "bool", "false" },
{ "Base64FormattingOptions", "Base64FormattingOptions.None" },
{ "S", "new S(0)" }
};
var ones = new Dictionary<string, string>()
{
{ "int", "1" },
{ "uint", "1" },
{ "short", "1" },
{ "ushort", "1" },
{ "byte", "1" },
{ "sbyte", "1" },
{ "long", "1" },
{ "ulong", "1" },
{ "double", "1" },
{ "float", "1" },
{ "decimal", "1" },
{ "char", "'b'" },
{ "bool", "true" },
{ "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" },
{ "S", "new S(1)" }
};
foreach (string t in types)
{
string s = source.Replace("TYPE", t).Replace("OP", oper).Replace("ZERO", zeros[t]).Replace("ONE", ones[t]);
var verifier = CompileAndVerify(source: s, expectedOutput: expected);
}
}
[Fact]
public void TestLiftedBuiltInBinaryArithmetic()
{
string[,] enumAddition =
{
//{ "sbyte", "Base64FormattingOptions"},
{ "byte", "Base64FormattingOptions"},
//{ "short", "Base64FormattingOptions"},
{ "ushort", "Base64FormattingOptions"},
//{ "int", "Base64FormattingOptions"},
//{ "uint", "Base64FormattingOptions"},
//{ "long", "Base64FormattingOptions"},
//{ "ulong", "Base64FormattingOptions"},
{ "char", "Base64FormattingOptions"},
//{ "decimal", "Base64FormattingOptions"},
//{ "double", "Base64FormattingOptions"},
//{ "float", "Base64FormattingOptions"},
{ "Base64FormattingOptions", "sbyte" },
{ "Base64FormattingOptions", "byte" },
{ "Base64FormattingOptions", "short" },
{ "Base64FormattingOptions", "ushort" },
{ "Base64FormattingOptions", "int" },
//{ "Base64FormattingOptions", "uint" },
//{ "Base64FormattingOptions", "long" },
//{ "Base64FormattingOptions", "ulong" },
{ "Base64FormattingOptions", "char" },
//{ "Base64FormattingOptions", "decimal" },
//{ "Base64FormattingOptions", "double" },
//{ "Base64FormattingOptions", "float" },
//{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
string[,] enumSubtraction =
{
{ "Base64FormattingOptions", "sbyte" },
//{ "Base64FormattingOptions", "byte" },
{ "Base64FormattingOptions", "short" },
{ "Base64FormattingOptions", "ushort" },
{ "Base64FormattingOptions", "int" },
//{ "Base64FormattingOptions", "uint" },
//{ "Base64FormattingOptions", "long" },
//{ "Base64FormattingOptions", "ulong" },
//{ "Base64FormattingOptions", "char" },
//{ "Base64FormattingOptions", "decimal" },
//{ "Base64FormattingOptions", "double" },
//{ "Base64FormattingOptions", "float" },
{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
string[,] numerics1 =
{
{ "sbyte", "sbyte" },
{ "sbyte", "byte" },
//{ "sbyte", "short" },
{ "sbyte", "ushort" },
//{ "sbyte", "int" },
{ "sbyte", "uint" },
//{ "sbyte", "long" },
//{ "sbyte", "ulong" },
//{ "sbyte", "char" },
{ "sbyte", "decimal" },
{ "sbyte", "double" },
//{ "sbyte", "float" },
//{ "byte", "sbyte" },
{ "byte", "byte" },
//{ "byte", "short" },
{ "byte", "ushort" },
//{ "byte", "int" },
{ "byte", "uint" },
//{ "byte", "long" },
{ "byte", "ulong" },
//{ "byte", "char" },
{ "byte", "decimal" },
//{ "byte", "double" },
{ "byte", "float" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
//{ "short", "ushort" },
{ "short", "int" },
//{ "short", "uint" },
{ "short", "long" },
//{ "short", "ulong" },
//{ "short", "char" },
{ "short", "decimal" },
//{ "short", "double" },
{ "short", "float" },
};
string[,] numerics2 =
{
//{ "ushort", "sbyte" },
//{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
//{ "ushort", "int" },
{ "ushort", "uint" },
{ "ushort", "long" },
//{ "ushort", "ulong" },
//{ "ushort", "char" },
//{ "ushort", "decimal" },
//{ "ushort", "double" },
{ "ushort", "float" },
{ "int", "sbyte" },
{ "int", "byte" },
//{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
//{ "int", "uint" },
{ "int", "long" },
// { "int", "ulong" },
{ "int", "char" },
//{ "int", "decimal" },
{ "int", "double" },
//{ "int", "float" },
//{ "uint", "sbyte" },
//{ "uint", "byte" },
{ "uint", "short" },
//{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "uint" },
{ "uint", "long" },
//{ "uint", "ulong" },
{ "uint", "char" },
//{ "uint", "decimal" },
//{ "uint", "double" },
{ "uint", "float" },
};
string[,] numerics3 =
{
{ "long", "sbyte" },
{ "long", "byte" },
//{ "long", "short" },
//{ "long", "ushort" },
//{ "long", "int" },
//{ "long", "uint" },
{ "long", "long" },
// { "long", "ulong" },
{ "long", "char" },
//{ "long", "decimal" },
//{ "long", "double" },
{ "long", "float" },
//{ "ulong", "sbyte" },
//{ "ulong", "byte" },
//{ "ulong", "short" },
{ "ulong", "ushort" },
//{ "ulong", "int" },
{ "ulong", "uint" },
//{ "ulong", "long" },
{ "ulong", "ulong" },
//{ "ulong", "char" },
{ "ulong", "decimal" },
{ "ulong", "double" },
//{ "ulong", "float" },
};
string[,] numerics4 =
{
{ "char", "sbyte" },
{ "char", "byte" },
{ "char", "short" },
{ "char", "ushort" },
//{ "char", "int" },
//{ "char", "uint" },
//{ "char", "long" },
{ "char", "ulong" },
{ "char", "char" },
//{ "char", "decimal" },
//{ "char", "double" },
{ "char", "float" },
//{ "decimal", "sbyte" },
//{ "decimal", "byte" },
//{ "decimal", "short" },
{ "decimal", "ushort" },
{ "decimal", "int" },
{ "decimal", "uint" },
{ "decimal", "long" },
//{ "decimal", "ulong" },
{ "decimal", "char" },
{ "decimal", "decimal" },
//{ "decimal", "double" },
//{ "decimal", "float" },
};
string[,] numerics5 =
{
//{ "double", "sbyte" },
{ "double", "byte" },
{ "double", "short" },
{ "double", "ushort" },
//{ "double", "int" },
{ "double", "uint" },
{ "double", "long" },
//{ "double", "ulong" },
{ "double", "char" },
//{ "double", "decimal" },
{ "double", "double" },
{ "double", "float" },
{ "float", "sbyte" },
//{ "float", "byte" },
//{ "float", "short" },
//{ "float", "ushort" },
{ "float", "int" },
//{ "float", "uint" },
//{ "float", "long" },
{ "float", "ulong" },
//{ "float", "char" },
//{ "float", "decimal" },
//{ "float", "double" },
{ "float", "float" },
};
string[,] shift1 =
{
{ "sbyte", "sbyte" },
{ "sbyte", "byte" },
{ "sbyte", "short" },
{ "sbyte", "ushort" },
{ "sbyte", "int" },
{ "sbyte", "char" },
{ "byte", "sbyte" },
{ "byte", "byte" },
{ "byte", "short" },
{ "byte", "ushort" },
{ "byte", "int" },
{ "byte", "char" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
{ "short", "ushort" },
{ "short", "int" },
{ "short", "char" },
{ "ushort", "sbyte" },
{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
{ "ushort", "int" },
{ "ushort", "char" },
};
string[,] shift2 =
{
{ "int", "sbyte" },
{ "int", "byte" },
{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
{ "int", "char" },
{ "uint", "sbyte" },
{ "uint", "byte" },
{ "uint", "short" },
{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "char" },
{ "long", "sbyte" },
{ "long", "byte" },
{ "long", "short" },
{ "long", "ushort" },
{ "long", "int" },
{ "long", "char" },
{ "ulong", "sbyte" },
{ "ulong", "byte" },
{ "ulong", "short" },
{ "ulong", "ushort" },
{ "ulong", "int" },
{ "ulong", "char" },
{ "char", "sbyte" },
{ "char", "byte" },
{ "char", "short" },
{ "char", "ushort" },
{ "char", "int" },
{ "char", "char" },
};
string[,] logical1 =
{
{ "sbyte", "sbyte" },
//{ "sbyte", "byte" },
{ "sbyte", "short" },
{ "sbyte", "ushort" },
{ "sbyte", "int" },
//{ "sbyte", "uint" },
{ "sbyte", "long" },
//{ "sbyte", "ulong" },
//{ "sbyte", "char" },
{ "byte", "sbyte" },
{ "byte", "byte" },
//{ "byte", "short" },
{ "byte", "ushort" },
//{ "byte", "int" },
{ "byte", "uint" },
//{ "byte", "long" },
//{ "byte", "ulong" },
{ "byte", "char" },
{ "short", "sbyte" },
{ "short", "byte" },
{ "short", "short" },
//{ "short", "ushort" },
{ "short", "int" },
//{ "short", "uint" },
{ "short", "long" },
//{ "short", "ulong" },
{ "short", "char" },
};
string[,] logical2 =
{
//{ "ushort", "sbyte" },
{ "ushort", "byte" },
{ "ushort", "short" },
{ "ushort", "ushort" },
//{ "ushort", "int" },
{ "ushort", "uint" },
//{ "ushort", "long" },
//{ "ushort", "ulong" },
//{ "ushort", "char" },
//{ "int", "sbyte" },
{ "int", "byte" },
//{ "int", "short" },
{ "int", "ushort" },
{ "int", "int" },
//{ "int", "uint" },
{ "int", "long" },
//{ "int", "ulong" },
//{ "int", "char" },
{ "uint", "sbyte" },
//{ "uint", "byte" },
{ "uint", "short" },
//{ "uint", "ushort" },
{ "uint", "int" },
{ "uint", "uint" },
//{ "uint", "long" },
//{ "uint", "ulong" },
{ "uint", "char" },
};
string[,] logical3 =
{
//{ "long", "sbyte" },
{ "long", "byte" },
//{ "long", "short" },
{ "long", "ushort" },
//{ "long", "int" },
{ "long", "uint" },
{ "long", "long" },
// { "long", "ulong" },
{ "long", "char" },
//{ "ulong", "sbyte" },
{ "ulong", "byte" },
//{ "ulong", "short" },
{ "ulong", "ushort" },
//{ "ulong", "int" },
{ "ulong", "uint" },
//{ "ulong", "long" },
{ "ulong", "ulong" },
//{ "ulong", "char" },
{ "char", "sbyte" },
//{ "char", "byte" },
//{ "char", "short" },
{ "char", "ushort" },
{ "char", "int" },
//{ "char", "uint" },
//{ "char", "long" },
{ "char", "ulong" },
{ "char", "char" },
{ "Base64FormattingOptions", "Base64FormattingOptions"},
};
// Use 2 instead of 0 so that we don't get divide by zero errors.
var twos = new Dictionary<string, string>()
{
{ "int", "2" },
{ "uint", "2" },
{ "short", "2" },
{ "ushort", "2" },
{ "byte", "2" },
{ "sbyte", "2" },
{ "long", "2" },
{ "ulong", "2" },
{ "double", "2" },
{ "float", "2" },
{ "decimal", "2" },
{ "char", "'\\u0002'" },
{ "Base64FormattingOptions", "Base64FormattingOptions.None" },
};
var ones = new Dictionary<string, string>()
{
{ "int", "1" },
{ "uint", "1" },
{ "short", "1" },
{ "ushort", "1" },
{ "byte", "1" },
{ "sbyte", "1" },
{ "long", "1" },
{ "ulong", "1" },
{ "double", "1" },
{ "float", "1" },
{ "decimal", "1" },
{ "char", "'\\u0001'" },
{ "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" },
};
var names = new Dictionary<string, string>()
{
{ "+", "plus" },
{ "-", "minus" },
{ "*", "times" },
{ "/", "divide" },
{ "%", "remainder" },
{ ">>", "rshift" },
{ "<<", "lshift" },
{ "&", "and" },
{ "|", "or" },
{ "^", "xor" }
};
var source = new StringBuilder(@"
using System;
class C
{
static void T(int x, bool b)
{
if (!b) throw new Exception(x.ToString());
}
static void F(int x, bool b)
{
if (b) throw new Exception(x.ToString());
}
");
string main = "static void Main() {";
string method = @"
static void METHOD_TYPEX_NAME_TYPEY()
{
TYPEX? xn0 = TWOX;
TYPEX? xn1 = ONEX;
TYPEX? xnn = null;
TYPEX x0 = TWOX;
TYPEX x1 = ONEX;
TYPEY? yn0 = TWOY;
TYPEY? yn1 = ONEY;
TYPEY? ynn = null;
TYPEY y0 = TWOY;
TYPEY y1 = ONEY;
F(1, (null OP yn0).HasValue);
F(2, (null OP yn1).HasValue);
F(3, (null OP ynn).HasValue);
F(4, (null OP y0).HasValue);
F(5, (null OP y1).HasValue);
F(6, (xn0 OP null).HasValue);
T(7, (xn0 OP yn0).Value == (x0 OP y0));
T(8, (xn0 OP yn1).Value == (x0 OP y1));
F(9, (xn0 OP ynn).HasValue);
T(10, (xn0 OP y0).Value == (x0 OP y0));
T(11, (xn0 OP y1).Value == (x0 OP y1));
F(12, (xn1 OP null).HasValue);
T(13, (xn1 OP yn0).Value == (x1 OP y0));
T(14, (xn1 OP yn1).Value == (x1 OP y1));
F(15, (xn1 OP ynn).HasValue);
T(16, (xn1 OP y0).Value == (x1 OP y0));
T(17, (xn1 OP y1).Value == (x1 OP y1));
F(18, (xnn OP null).HasValue);
F(19, (xnn OP yn0).HasValue);
F(20, (xnn OP yn1).HasValue);
F(21, (xnn OP ynn).HasValue);
F(22, (xnn OP y0).HasValue);
F(23, (xnn OP y1).HasValue);
F(24, (x0 OP null).HasValue);
T(25, (x0 OP yn0).Value == (x0 OP y0));
T(26, (x0 OP yn1).Value == (x0 OP y1));
F(27, (x0 OP ynn).HasValue);
F(28, (x1 OP null).HasValue);
T(29, (x1 OP yn0).Value == (x1 OP y0));
T(30, (x1 OP yn1).Value == (x1 OP y1));
F(31, (x1 OP ynn).HasValue);
}";
List<Tuple<string, string[,]>> items = new List<Tuple<string, string[,]>>()
{
Tuple.Create("*", numerics1),
Tuple.Create("/", numerics2),
Tuple.Create("%", numerics3),
Tuple.Create("+", numerics4),
Tuple.Create("+", enumAddition),
Tuple.Create("-", numerics5),
// UNDONE: Overload resolution of "enum - null" ,
// UNDONE: so this test is disabled:
// UNDONE: Tuple.Create("-", enumSubtraction),
Tuple.Create(">>", shift1),
Tuple.Create("<<", shift2),
Tuple.Create("&", logical1),
Tuple.Create("|", logical2),
Tuple.Create("^", logical3)
};
int m = 0;
foreach (var item in items)
{
string oper = item.Item1;
string[,] types = item.Item2;
for (int i = 0; i < types.GetLength(0); ++i)
{
++m;
string typeX = types[i, 0];
string typeY = types[i, 1];
source.Append(method
.Replace("METHOD", "M" + m)
.Replace("TYPEX", typeX)
.Replace("TYPEY", typeY)
.Replace("OP", oper)
.Replace("NAME", names[oper])
.Replace("TWOX", twos[typeX])
.Replace("ONEX", ones[typeX])
.Replace("TWOY", twos[typeY])
.Replace("ONEY", ones[typeY]));
main += "M" + m + "_" + typeX + "_" + names[oper] + "_" + typeY + "();\n";
}
}
source.Append(main);
source.Append("} }");
var verifier = CompileAndVerify(source: source.ToString(), expectedOutput: "");
}
[Fact]
public void TestLiftedUserDefinedBinaryArithmetic()
{
string source = @"
using System;
struct SX
{
public string str;
public SX(string str) { this.str = str; }
public SX(char c) { this.str = c.ToString(); }
public static SZ operator +(SX sx, SY sy) { return new SZ(sx.str + '+' + sy.str); }
public static SZ operator -(SX sx, SY sy) { return new SZ(sx.str + '-' + sy.str); }
public static SZ operator *(SX sx, SY sy) { return new SZ(sx.str + '*' + sy.str); }
public static SZ operator /(SX sx, SY sy) { return new SZ(sx.str + '/' + sy.str); }
public static SZ operator %(SX sx, SY sy) { return new SZ(sx.str + '%' + sy.str); }
public static SZ operator &(SX sx, SY sy) { return new SZ(sx.str + '&' + sy.str); }
public static SZ operator |(SX sx, SY sy) { return new SZ(sx.str + '|' + sy.str); }
public static SZ operator ^(SX sx, SY sy) { return new SZ(sx.str + '^' + sy.str); }
public static SZ operator >>(SX sx, int i) { return new SZ(sx.str + '>' + '>' + i.ToString()); }
public static SZ operator <<(SX sx, int i) { return new SZ(sx.str + '<' + '<' + i.ToString()); }
}
struct SY
{
public string str;
public SY(string str) { this.str = str; }
public SY(char c) { this.str = c.ToString(); }
}
struct SZ
{
public string str;
public SZ(string str) { this.str = str; }
public SZ(char c) { this.str = c.ToString(); }
public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; }
public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class C
{
static void T(bool b)
{
if (!b) throw new Exception();
}
static void F(bool b)
{
if (b) throw new Exception();
}
static void Main()
{
SX sx = new SX('a');
SX? sxn = sx;
SX? sxnn = null;
SY sy = new SY('b');
SY? syn = sy;
SY? synn = null;
int i1 = 1;
int? i1n = 1;
int? i1nn = null;
";
source += @"
T((sx + syn).Value == (sx + sy));
F((sx - synn).HasValue);
F((sx * null).HasValue);
T((sxn % sy).Value == (sx % sy));
T((sxn / syn).Value == (sx / sy));
F((sxn ^ synn).HasValue);
F((sxn & null).HasValue);
F((sxnn | sy).HasValue);
F((sxnn ^ syn).HasValue);
F((sxnn + synn).HasValue);
F((sxnn - null).HasValue);";
source += @"
T((sx << i1n).Value == (sx << i1));
F((sx >> i1nn).HasValue);
F((sx << null).HasValue);
T((sxn >> i1).Value == (sx >> i1));
T((sxn << i1n).Value == (sx << i1));
F((sxn >> i1nn).HasValue);
F((sxn << null).HasValue);
F((sxnn >> i1).HasValue);
F((sxnn << i1n).HasValue);
F((sxnn >> i1nn).HasValue);
F((sxnn << null).HasValue);";
source += "}}";
var verifier = CompileAndVerify(source: source, expectedOutput: "");
}
[Fact]
public void TestLiftedBoolLogicOperators()
{
string source = @"
using System;
class C
{
static void T(int x, bool? b) { if (!(b.HasValue && b.Value)) throw new Exception(x.ToString()); }
static void F(int x, bool? b) { if (!(b.HasValue && !b.Value)) throw new Exception(x.ToString()); }
static void N(int x, bool? b) { if (b.HasValue) throw new Exception(x.ToString()); }
static void Main()
{
bool bt = true;
bool bf = false;
bool? bnt = bt;
bool? bnf = bf;
bool? bnn = null;
T(1, true & bnt);
T(2, true & bnt);
F(3, true & bnf);
N(4, true & null);
N(5, true & bnn);
T(6, bt & bnt);
T(7, bt & bnt);
F(8, bt & bnf);
N(9, bt & null);
N(10, bt & bnn);
T(11, bnt & true);
T(12, bnt & bt);
T(13, bnt & bnt);
F(14, bnt & false);
F(15, bnt & bf);
F(16, bnt & bnf);
N(17, bnt & null);
N(18, bnt & bnn);
F(19, false & bnt);
F(20, false & bnf);
F(21, false & null);
F(22, false & bnn);
F(23, bf & bnt);
F(24, bf & bnf);
F(25, bf & null);
F(26, bf & bnn);
F(27, bnf & true);
F(28, bnf & bt);
F(29, bnf & bnt);
F(30, bnf & false);
F(31, bnf & bf);
F(32, bnf & bnf);
F(33, bnf & null);
F(34, bnf & bnn);
N(35, null & true);
N(36, null & bt);
N(37, null & bnt);
F(38, null & false);
F(39, null & bf);
F(40, null & bnf);
N(41, null & bnn);
N(42, bnn & true);
N(43, bnn & bt);
N(44, bnn & bnt);
F(45, bnn & false);
F(46, bnn & bf);
F(47, bnn & bnf);
N(48, bnn & null);
N(49, bnn & bnn);
T(51, true | bnt);
T(52, true | bnt);
T(53, true | bnf);
T(54, true | null);
T(55, true | bnn);
T(56, bt | bnt);
T(57, bt | bnt);
T(58, bt | bnf);
T(59, bt | null);
T(60, bt | bnn);
T(61, bnt | true);
T(62, bnt | bt);
T(63, bnt | bnt);
T(64, bnt | false);
T(65, bnt | bf);
T(66, bnt | bnf);
T(67, bnt | null);
T(68, bnt | bnn);
T(69, false | bnt);
F(70, false | bnf);
N(71, false | null);
N(72, false | bnn);
T(73, bf | bnt);
F(74, bf | bnf);
N(75, bf | null);
N(76, bf | bnn);
T(77, bnf | true);
T(78, bnf | bt);
T(79, bnf | bnt);
F(80, bnf | false);
F(81, bnf | bf);
F(82, bnf | bnf);
N(83, bnf | null);
N(84, bnf | bnn);
T(85, null | true);
T(86, null | bt);
T(87, null | bnt);
N(88, null | false);
N(89, null | bf);
N(90, null | bnf);
N(91, null | bnn);
T(92, bnn | true);
T(93, bnn | bt);
T(94, bnn | bnt);
N(95, bnn | false);
N(96, bnn | bf);
N(97, bnn | bnf);
N(98, bnn | null);
N(99, bnn | bnn);
F(101, true ^ bnt);
F(102, true ^ bnt);
T(103, true ^ bnf);
N(104, true ^ null);
N(105, true ^ bnn);
F(106, bt ^ bnt);
F(107, bt ^ bnt);
T(108, bt ^ bnf);
N(109, bt ^ null);
N(110, bt ^ bnn);
F(111, bnt ^ true);
F(112, bnt ^ bt);
F(113, bnt ^ bnt);
T(114, bnt ^ false);
T(115, bnt ^ bf);
T(116, bnt ^ bnf);
N(117, bnt ^ null);
N(118, bnt ^ bnn);
T(119, false ^ bnt);
F(120, false ^ bnf);
N(121, false ^ null);
N(122, false ^ bnn);
T(123, bf ^ bnt);
F(124, bf ^ bnf);
N(125, bf ^ null);
N(126, bf ^ bnn);
T(127, bnf ^ true);
T(128, bnf ^ bt);
T(129, bnf ^ bnt);
F(130, bnf ^ false);
F(131, bnf ^ bf);
F(132, bnf ^ bnf);
N(133, bnf ^ null);
N(134, bnf ^ bnn);
N(135, null ^ true);
N(136, null ^ bt);
N(137, null ^ bnt);
N(138, null ^ false);
N(139, null ^ bf);
N(140, null ^ bnf);
N(141, null ^ bnn);
N(142, bnn ^ true);
N(143, bnn ^ bt);
N(144, bnn ^ bnt);
N(145, bnn ^ false);
N(146, bnn ^ bf);
N(147, bnn ^ bnf);
N(148, bnn ^ null);
N(149, bnn ^ bnn);
}
}";
var verifier = CompileAndVerify(source: source, expectedOutput: "");
}
[Fact]
public void TestLiftedCompoundAssignment()
{
string source = @"
using System;
class C
{
static void Main()
{
int? n = 1;
int a = 2;
int? b = 3;
short c = 4;
short? d = 5;
int? e = null;
n += a;
T(1, n == 3);
n += b;
T(2, n == 6);
n += c;
T(3, n == 10);
n += d;
T(4, n == 15);
n += e;
F(5, n.HasValue);
n += a;
F(6, n.HasValue);
n += b;
F(7, n.HasValue);
n += c;
F(8, n.HasValue);
n += d;
F(9, n.HasValue);
Console.WriteLine(123);
}
static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); }
static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); }
}";
var verifier = CompileAndVerify(source: source, expectedOutput: "123");
}
#region "Regression"
[Fact, WorkItem(543837, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543837")]
public void Test11827()
{
string source2 = @"
using System;
class Program
{
static void Main()
{
Func<decimal?, decimal?> lambda = a => { return checked(a * a); };
Console.WriteLine(0);
}
}";
var verifier = CompileAndVerify(source: source2, expectedOutput: "0");
}
[Fact, WorkItem(544001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544001")]
public void NullableUsedInUsingStatement()
{
string source = @"
using System;
struct S : IDisposable
{
public void Dispose()
{
Console.WriteLine(123);
}
static void Main()
{
using (S? r = new S())
{
Console.Write(r);
}
}
}
";
CompileAndVerify(source: source, expectedOutput: @"S123");
}
[Fact, WorkItem(544002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544002")]
public void NullableUserDefinedUnary02()
{
string source = @"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator +(S? s) { return s.HasValue ? 10 : -10; }
public static int operator -(S s) { return 2; }
public static int operator -(S? s) { return s.HasValue ? 20 : -20; }
public static int operator !(S s) { return 3; }
public static int operator !(S? s) { return s.HasValue ? 30 : -30; }
public static int operator ~(S s) { return 4; }
public static int operator ~(S? s) { return s.HasValue ? 40 : -40; }
public static void Main()
{
S? sq = new S();
Console.Write(+sq);
Console.Write(-sq);
Console.Write(!sq);
Console.Write(~sq);
sq = null;
Console.Write(+sq);
Console.Write(-sq);
Console.Write(!sq);
Console.Write(~sq);
}
}
";
CompileAndVerify(source: source, expectedOutput: @"10203040-10-20-30-40");
}
[Fact, WorkItem(544005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544005")]
public void NoNullableValueFromOptionalParam()
{
string source = @"
class Test
{
static void M(
double? d0 = null,
double? d1 = 1.11,
double? d2 = 2,
double? d3 = default(double?),
double d4 = 4,
double d5 = default(double),
string s6 = ""6"",
string s7 = null,
string s8 = default(string))
{
System.Console.WriteLine(""0:{0} 1:{1} 2:{2} 3:{3} 4:{4} 5:{5} 6:{6} 7:{7} 8:{8}"",
d0, d1.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d2, d3, d4, d5, s6, s7, s8);
}
static void Main()
{
M();
}
}
";
string expected = @"0: 1:1.11 2:2 3: 4:4 5:0 6:6 7: 8:";
var verifier = CompileAndVerify(source, expectedOutput: expected);
}
[Fact, WorkItem(544006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544006")]
public void ConflictImportedMethodWithNullableOptionalParam()
{
string source = @"
public class Parent
{
public int Goo(int? d = 0) { return (int)d; }
}
";
string source2 = @"
public class Parent
{
public int Goo(int? d = 0) { return (int)d; }
}
public class Test
{
public static void Main()
{
Parent p = new Parent();
System.Console.Write(p.Goo(0));
}
}
";
var complib = CreateCompilation(
source,
options: TestOptions.ReleaseDll,
assemblyName: "TestDLL");
var comp = CreateCompilation(
source2,
references: new MetadataReference[] { complib.EmitToImageReference() },
options: TestOptions.ReleaseExe,
assemblyName: "TestEXE");
comp.VerifyDiagnostics(
// (11,9): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''.
// Parent p = new Parent();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent"),
// (11,24): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''.
// Parent p = new Parent();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent")
);
CompileAndVerify(comp, expectedOutput: @"0");
}
[Fact, WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")]
public void BindDelegateToObjectMethods()
{
string source = @"
using System;
public class Test
{
delegate int I();
static void Main()
{
int? x = 123;
Func<string> d1 = x.ToString;
I d2 = x.GetHashCode;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(544909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544909")]
public void OperationOnEnumNullable()
{
string source = @"
using System;
public class NullableTest
{
public enum E : short { Zero = 0, One = 1, Max = System.Int16.MaxValue, Min = System.Int16.MinValue }
static E? NULL = null;
public static void Main()
{
E? nub = 0;
Test(nub.HasValue); // t
nub = NULL;
Test(nub.HasValue); // f
nub = ~nub;
Test(nub.HasValue); // f
nub = NULL++;
Test(nub.HasValue); // f
nub = 0;
nub++;
Test(nub.HasValue); // t
Test(nub.GetValueOrDefault() == E.One); // t
nub = E.Max;
nub++;
Test(nub.GetValueOrDefault() == E.Min); // t
}
static void Test(bool b)
{
Console.Write(b ? 't' : 'f');
}
}
";
CompileAndVerify(source, expectedOutput: "tfffttt");
}
[Fact, WorkItem(544583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544583")]
public void ShortCircuitOperatorsOnNullable()
{
string source = @"
class A
{
static void Main()
{
bool? b1 = true, b2 = false;
var bb = b1 && b2;
bb = b1 || b2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,18): error CS0019: Operator '&&' cannot be applied to operands of type 'bool?' and 'bool?'
// var bb = b1 && b2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 && b2").WithArguments("&&", "bool?", "bool?"),
// (8,14): error CS0019: Operator '||' cannot be applied to operands of type 'bool?' and 'bool?'
// bb = b1 || b2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 || b2").WithArguments("||", "bool?", "bool?")
);
}
[Fact]
public void ShortCircuitLiftedUserDefinedOperators()
{
// This test illustrates a bug in the native compiler which Roslyn fixes.
// The native compiler disallows a *lifted* & operator from being used as an &&
// operator, but allows a *nullable* & operator to be used as an && operator.
// There is no good reason for this discrepancy; either both should be legal
// (because we can obviously generate good code that does what the user wants)
// or we should disallow both.
string source = @"
using System;
struct C
{
public bool b;
public C(bool b) { this.b = b; }
public static C operator &(C c1, C c2) { return new C(c1.b & c2.b); }
public static C operator |(C c1, C c2) { return new C(c1.b | c2.b); }
// null is false
public static bool operator true(C? c) { return c == null ? false : c.Value.b; }
public static bool operator false(C? c) { return c == null ? true : !c.Value.b; }
public static C? True() { Console.Write('t'); return new C(true); }
public static C? False() { Console.Write('f'); return new C(false); }
public static C? Null() { Console.Write('n'); return new C?(); }
}
struct D
{
public bool b;
public D(bool b) { this.b = b; }
public static D? operator &(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b & d2.Value.b)) : (D?)null; }
public static D? operator |(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b | d2.Value.b)) : (D?)null; }
// null is false
public static bool operator true(D? d) { return d == null ? false : d.Value.b; }
public static bool operator false(D? d) { return d == null ? true : !d.Value.b; }
public static D? True() { Console.Write('t'); return new D(true); }
public static D? False() { Console.Write('f'); return new D(false); }
public static D? Null() { Console.Write('n'); return new D?(); }
}
class P
{
static void Main()
{
D?[] results1 =
{
D.True() && D.True(), // tt --> t
D.True() && D.False(), // tf --> f
D.True() && D.Null(), // tn --> n
D.False() && D.True(), // f --> f
D.False() && D.False(), // f --> f
D.False() && D.Null(), // f --> f
D.Null() && D.True(), // n --> n
D.Null() && D.False(), // n --> n
D.Null() && D.Null() // n --> n
};
Console.WriteLine();
foreach(D? r in results1)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
C?[] results2 =
{
C.True() && C.True(),
C.True() && C.False(),
C.True() && C.Null(),
C.False() && C.True(),
C.False() && C.False(),
C.False() && C.Null(),
C.Null() && C.True(),
C.Null() && C.False(),
C.Null() && C.Null()
};
Console.WriteLine();
foreach(C? r in results2)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
D?[] results3 =
{
D.True() || D.True(), // t --> t
D.True() || D.False(), // t --> t
D.True() || D.Null(), // t --> t
D.False() || D.True(), // ft --> t
D.False() || D.False(), // ff --> f
D.False() || D.Null(), // fn --> n
D.Null() || D.True(), // nt --> n
D.Null() || D.False(), // nf --> n
D.Null() || D.Null() // nn --> n
};
Console.WriteLine();
foreach(D? r in results3)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
Console.WriteLine();
C?[] results4 =
{
C.True() || C.True(),
C.True() || C.False(),
C.True() || C.Null(),
C.False() || C.True(),
C.False() || C.False(),
C.False() || C.Null(),
C.Null() || C.True(),
C.Null() || C.False(),
C.Null() || C.Null()
};
Console.WriteLine();
foreach(C? r in results4)
Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f');
}
}
";
string expected = @"tttftnfffnnn
tfnfffnnn
tttftnfffnnn
tfnfffnnn
tttftfffnntnfnn
ttttfnnnn
tttftfffnntnfnn
ttttfnnnn";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact, WorkItem(529530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529530"), WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void NullableEnumMinusNull()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Console.WriteLine((xn0 - null).HasValue);
}
}";
CompileAndVerify(source, expectedOutput: "False").VerifyDiagnostics(
// (9,28): warning CS0458: The result of the expression is always 'null' of type 'int?'
// Console.WriteLine((xn0 - null).HasValue);
Diagnostic(ErrorCode.WRN_AlwaysNull, "xn0 - null").WithArguments("int?").WithLocation(9, 28)
);
}
[Fact]
public void NullableNullEquality()
{
var source = @"
using System;
public struct S
{
public static void Main()
{
S? s = new S();
Console.WriteLine(null == s);
}
}";
CompileAndVerify(source, expectedOutput: "False");
}
[Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")]
public void Op_ExplicitImplicitOnNullable()
{
var source = @"
using System;
class Test
{
static void Main()
{
var x = (int?).op_Explicit(1);
var y = (Nullable<int>).op_Implicit(2);
}
}
";
// VB now allow these syntax, but C# does NOT (spec said)
// Dev11 & Roslyn: (8,23): error CS1525: Invalid expression term '.'
// ---
// Dev11: error CS0118: 'int?' is a 'type' but is used like a 'variable'
// Roslyn: (9,18): error CS0119: 'int?' is a type, which is not valid in the given context
// Roslyn: (9,33): error CS0571: 'int?.implicit operator int?(int)': cannot explicitly call operator or accessor
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments("."),
Diagnostic(ErrorCode.ERR_BadSKunknown, "Nullable<int>").WithArguments("int?", "type"),
Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Implicit").WithArguments("int?.implicit operator int?(int)")
);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Portable/Binding/Binder_Operators.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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
' Binding of binary and unary operators is implemented in this part.
Partial Friend Class Binder
Private Function BindIsExpression(
node As BinaryExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Kind = SyntaxKind.IsExpression OrElse node.Kind = SyntaxKind.IsNotExpression)
Dim [isNot] As Boolean = (node.Kind = SyntaxKind.IsNotExpression)
' The function below will make sure they are RValues.
Dim left As BoundExpression = BindExpression(node.Left, diagnostics)
Dim right As BoundExpression = BindExpression(node.Right, diagnostics)
Return BindIsExpression(left, right, node, [isNot], diagnostics)
End Function
Private Function BindIsExpression(
left As BoundExpression,
right As BoundExpression,
node As SyntaxNode,
[isNot] As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
left = MakeRValue(left, diagnostics)
right = MakeRValue(right, diagnostics)
left = ValidateAndConvertIsExpressionArgument(left, right, [isNot], diagnostics)
right = ValidateAndConvertIsExpressionArgument(right, left, [isNot], diagnostics)
Dim result As BoundExpression
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, node, diagnostics)
result = New BoundBinaryOperator(node,
If([isNot], BinaryOperatorKind.IsNot, BinaryOperatorKind.Is),
left,
right,
checked:=False,
type:=booleanType,
hasErrors:=booleanType.IsErrorType())
' TODO: Add rewrite for Nullable.
Return result
End Function
''' <summary>
''' Validate and apply appropriate conversion for the target argument of Is/IsNot expression.
''' </summary>
Private Function ValidateAndConvertIsExpressionArgument(
targetArgument As BoundExpression,
otherArgument As BoundExpression,
[isNot] As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetArgumentType As TypeSymbol = targetArgument.Type
Dim result As BoundExpression
If targetArgument.IsNothingLiteral() Then
result = targetArgument
ElseIf targetArgumentType.IsErrorType() Then
result = targetArgument
ElseIf targetArgumentType.IsReferenceType Then
result = ApplyImplicitConversion(targetArgument.Syntax,
GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics),
targetArgument,
diagnostics)
ElseIf targetArgumentType.IsNullableType() Then
If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOperatorNullable1, ERRID.ERR_IsOperatorNullable1),
targetArgumentType)
End If
result = targetArgument
ElseIf targetArgumentType.IsTypeParameter() AndAlso Not targetArgumentType.IsValueType Then
If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOperatorGenericParam1, ERRID.ERR_IsOperatorGenericParam1),
targetArgumentType)
End If
' If any of the left or right operands of the Is or IsNot operands
' are entities of type parameters types, then they need to be boxed.
result = ApplyImplicitConversion(targetArgument.Syntax,
GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics),
targetArgument,
diagnostics)
Else
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOpRequiresReferenceTypes1, ERRID.ERR_IsOperatorRequiresReferenceTypes1),
targetArgumentType)
result = targetArgument
End If
Return result
End Function
Private Function BindBinaryOperator(
node As BinaryExpressionSyntax,
isOperandOfConditionalBranch As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
' Some tools, such as ASP .NET, generate expressions containing thousands
' of string concatenations. For this reason, for string concatenations,
' avoid the usual recursion along the left side of the parse. Also, attempt
' to flatten whole sequences of string literal concatenations to avoid
' allocating space for intermediate results.
Dim preliminaryOperatorKind As BinaryOperatorKind = OverloadResolution.MapBinaryOperatorKind(node.Kind)
Dim propagateIsOperandOfConditionalBranch = isOperandOfConditionalBranch AndAlso
(preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse
preliminaryOperatorKind = BinaryOperatorKind.OrElse)
Dim binary As BinaryExpressionSyntax = node
Dim child As ExpressionSyntax
Do
child = binary.Left
Select Case child.Kind
Case SyntaxKind.AddExpression,
SyntaxKind.ConcatenateExpression,
SyntaxKind.LikeExpression,
SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.SubtractExpression,
SyntaxKind.MultiplyExpression,
SyntaxKind.ExponentiateExpression,
SyntaxKind.DivideExpression,
SyntaxKind.ModuloExpression,
SyntaxKind.IntegerDivideExpression,
SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression,
SyntaxKind.ExclusiveOrExpression,
SyntaxKind.OrExpression,
SyntaxKind.AndExpression
If propagateIsOperandOfConditionalBranch Then
Exit Do
End If
Case SyntaxKind.OrElseExpression,
SyntaxKind.AndAlsoExpression
Exit Select
Case Else
Exit Do
End Select
binary = DirectCast(child, BinaryExpressionSyntax)
Loop
Dim left As BoundExpression = BindValue(child, diagnostics, propagateIsOperandOfConditionalBranch)
Do
binary = DirectCast(child.Parent, BinaryExpressionSyntax)
Dim right As BoundExpression = BindValue(binary.Right, diagnostics, propagateIsOperandOfConditionalBranch)
left = BindBinaryOperator(binary, left, right, binary.OperatorToken.Kind,
OverloadResolution.MapBinaryOperatorKind(binary.Kind),
If(binary Is node, isOperandOfConditionalBranch, propagateIsOperandOfConditionalBranch),
diagnostics)
child = binary
Loop While child IsNot node
Return left
End Function
Private Function BindBinaryOperator(
node As SyntaxNode,
left As BoundExpression,
right As BoundExpression,
operatorTokenKind As SyntaxKind,
preliminaryOperatorKind As BinaryOperatorKind,
isOperandOfConditionalBranch As Boolean,
diagnostics As BindingDiagnosticBag,
Optional isSelectCase As Boolean = False
) As BoundExpression
Debug.Assert(left.IsValue)
Debug.Assert(right.IsValue)
Dim originalDiagnostics = diagnostics
If (left.HasErrors OrElse right.HasErrors) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
diagnostics = BindingDiagnosticBag.Discarded
End If
' Deal with NOTHING literal as an input.
ConvertNothingLiterals(preliminaryOperatorKind, left, right, diagnostics)
left = MakeRValue(left, diagnostics)
right = MakeRValue(right, diagnostics)
If (left.HasErrors OrElse right.HasErrors) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim leftType As TypeSymbol = left.Type
Dim rightType As TypeSymbol = right.Type
Dim leftIsDBNull As Boolean = leftType.IsDBNullType()
Dim rightIsDBNull As Boolean = rightType.IsDBNullType()
'§11.16 Concatenation Operator
'A System.DBNull value is converted to the literal Nothing typed as String.
If (preliminaryOperatorKind = BinaryOperatorKind.Concatenate AndAlso leftIsDBNull <> rightIsDBNull) OrElse
(preliminaryOperatorKind = BinaryOperatorKind.Add AndAlso
((leftType.IsStringType() AndAlso rightIsDBNull) OrElse (leftIsDBNull AndAlso rightType.IsStringType))) Then
Debug.Assert(leftIsDBNull Xor rightIsDBNull)
If leftIsDBNull Then
leftType = SubstituteDBNullWithNothingString(left, rightType, diagnostics)
Else
rightType = SubstituteDBNullWithNothingString(right, leftType, diagnostics)
End If
End If
' For comparison operators, the result type computed here is not
' the result type of the comparison (which is typically boolean),
' but is the type to which the operands are to be converted. For
' other operators, the type computed here is both the result type
' and the common operand type.
Dim intrinsicOperatorType As SpecialType = SpecialType.None
Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim operatorKind As BinaryOperatorKind = OverloadResolution.ResolveBinaryOperator(preliminaryOperatorKind, left, right, Me,
True,
intrinsicOperatorType,
userDefinedOperator,
useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If operatorKind = BinaryOperatorKind.UserDefined Then
Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue,
userDefinedOperator.BestResult.Value.Candidate,
Nothing)
If bestCandidate Is Nothing OrElse
Not bestCandidate.IsLifted OrElse
(OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(1).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then
If preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse Then
Return BindUserDefinedShortCircuitingOperator(node, preliminaryOperatorKind, left, right,
userDefinedOperator, diagnostics)
Else
Return BindUserDefinedNonShortCircuitingBinaryOperator(node, preliminaryOperatorKind, left, right,
userDefinedOperator, diagnostics)
End If
End If
operatorKind = BinaryOperatorKind.Error
End If
If operatorKind = BinaryOperatorKind.Error Then
ReportUndefinedOperatorError(node, left, right, operatorTokenKind, preliminaryOperatorKind, diagnostics)
Return New BoundBinaryOperator(node, preliminaryOperatorKind Or BinaryOperatorKind.Error, left, right, CheckOverflow, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
' We are dealing with intrinsic operator
' Get the symbol for operand type
Dim operandType As TypeSymbol
If intrinsicOperatorType = SpecialType.None Then
' Must be a bitwise operation with enum type.
Debug.Assert(leftType.GetNullableUnderlyingTypeOrSelf().IsEnumType() AndAlso
leftType.GetNullableUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(rightType.GetNullableUnderlyingTypeOrSelf()))
If (operatorKind And BinaryOperatorKind.Lifted) = 0 OrElse leftType.IsNullableType() Then
operandType = leftType
Else
Debug.Assert(rightType.IsNullableType())
operandType = rightType
End If
Else
operandType = GetSpecialTypeForBinaryOperator(node, leftType, rightType, intrinsicOperatorType,
(operatorKind And BinaryOperatorKind.Lifted) <> 0, diagnostics)
End If
' Get the symbol for result type
Dim operatorResultType As TypeSymbol = operandType
Dim forceToBooleanType As TypeSymbol = Nothing
Select Case preliminaryOperatorKind
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Like
If OptionCompareText AndAlso (operandType.IsObjectType() OrElse operandType.IsStringType()) Then
operatorKind = operatorKind Or BinaryOperatorKind.CompareText
End If
If Not operatorResultType.IsObjectType() OrElse
(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) Then
Dim booleanType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Boolean,
False, diagnostics)
If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then
operatorResultType = GetNullableTypeForBinaryOperator(leftType, rightType, booleanType)
If (preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals) AndAlso
(IsKnownToBeNullableNothing(left) OrElse IsKnownToBeNullableNothing(right)) Then
ReportDiagnostic(diagnostics, node,
ErrorFactory.ErrorInfo(
If(preliminaryOperatorKind = BinaryOperatorKind.Equals,
ERRID.WRN_EqualToLiteralNothing, ERRID.WRN_NotEqualToLiteralNothing)))
End If
Else
If Not operatorResultType.IsObjectType() Then
operatorResultType = booleanType
Else
' I believe this is just an optimization to prevent Object from bubbling up the tree.
Debug.Assert(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like)
forceToBooleanType = booleanType
End If
End If
End If
End Select
If operandType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse
operatorResultType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse
(forceToBooleanType IsNot Nothing AndAlso forceToBooleanType.GetNullableUnderlyingTypeOrSelf().IsErrorType()) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim hasError As Boolean = False
' Option Strict disallows all operations on Object operands. Or, at least, warn.
If OptionStrict = VisualBasic.OptionStrict.On Then
Dim reportedAnEror As Boolean = False
If leftType.IsObjectType Then
ReportBinaryOperatorOnObject(operatorTokenKind, left, preliminaryOperatorKind, diagnostics)
reportedAnEror = True
End If
If rightType.IsObjectType() Then
ReportBinaryOperatorOnObject(operatorTokenKind, right, preliminaryOperatorKind, diagnostics)
reportedAnEror = True
End If
If reportedAnEror Then
hasError = True
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then 'warn if option strict is off
If Not isSelectCase OrElse preliminaryOperatorKind <> BinaryOperatorKind.OrElse Then
Dim errorId = If(isSelectCase, ERRID.WRN_ObjectMathSelectCase,
If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_ObjectMath1,
If(preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.WRN_ObjectMath1Not, ERRID.WRN_ObjectMath2)))
If leftType.IsObjectType Then
ReportDiagnostic(diagnostics, left.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind))
End If
If rightType.IsObjectType Then
ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind))
End If
End If
End If
' Apply conversions to operands.
Dim explicitSemanticForConcatArgument As Boolean = False
' Concatenation will apply conversions to its operands as if the
' conversions were explicit. Effectively, the use of the concatenation
' operator is treated as an explicit conversion to String.
If preliminaryOperatorKind = BinaryOperatorKind.Concatenate Then
explicitSemanticForConcatArgument = True
Debug.Assert((operatorKind And BinaryOperatorKind.Lifted) = 0)
If operandType.IsStringType() Then
If left.Type.IsNullableType Then
left = ForceLiftToEmptyString(left, operandType, diagnostics)
End If
If right.Type.IsNullableType Then
right = ForceLiftToEmptyString(right, operandType, diagnostics)
End If
End If
End If
Dim beforeConversion As BoundExpression = left
left = ApplyConversion(left.Syntax, operandType, left, explicitSemanticForConcatArgument, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
If explicitSemanticForConcatArgument AndAlso left IsNot beforeConversion AndAlso left.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(left, BoundConversion)
left = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False,
constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt,
type:=conversion.Type)
End If
If (preliminaryOperatorKind = BinaryOperatorKind.LeftShift OrElse preliminaryOperatorKind = BinaryOperatorKind.RightShift) AndAlso
Not operandType.IsObjectType() Then
Dim rightTargetType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Int32,
False, diagnostics)
'§11.18 Shift Operators
'The type of the right operand must be implicitly convertible to Integer
' If operator is lifted, convert right operand to Nullable(Of Integer)
If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then
rightTargetType = GetNullableTypeForBinaryOperator(leftType, rightType, rightTargetType)
End If
right = ApplyImplicitConversion(right.Syntax, rightTargetType, right, diagnostics)
Else
beforeConversion = right
right = ApplyConversion(right.Syntax, operandType, right, explicitSemanticForConcatArgument, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
If explicitSemanticForConcatArgument AndAlso right IsNot beforeConversion AndAlso right.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(right, BoundConversion)
right = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False,
constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt,
type:=conversion.Type)
End If
End If
If (operatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Add AndAlso operatorResultType.IsStringType() Then
' Transform the addition into a string concatenation. This won't use a runtime helper - it will turn into System.String::Concat
operatorKind = (operatorKind And (Not BinaryOperatorKind.OpMask))
operatorKind = operatorKind Or BinaryOperatorKind.Concatenate
End If
' Perform constant folding.
Dim value As ConstantValue = Nothing
If Not (left.HasErrors OrElse right.HasErrors) Then
Dim integerOverflow As Boolean = False
Dim divideByZero As Boolean = False
Dim lengthOutOfLimit As Boolean = False
value = OverloadResolution.TryFoldConstantBinaryOperator(operatorKind,
left,
right,
operatorResultType,
integerOverflow,
divideByZero,
lengthOutOfLimit)
If value IsNot Nothing Then
If divideByZero Then
Debug.Assert(value.IsBad)
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ZeroDivide))
ElseIf lengthOutOfLimit Then
Debug.Assert(value.IsBad)
ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(ERRID.ERR_ConstantStringTooLong))
ElseIf (value.IsBad OrElse integerOverflow) Then
' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior.
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, operatorResultType))
' there should be no constant value in case of overflows.
If Not value.IsBad Then
value = ConstantValue.Bad
End If
End If
End If
End If
Dim result As BoundExpression = New BoundBinaryOperator(node, operatorKind Or If(isOperandOfConditionalBranch, BinaryOperatorKind.IsOperandOfConditionalBranch, Nothing),
left, right, CheckOverflow, value, operatorResultType, hasError)
If forceToBooleanType IsNot Nothing Then
Debug.Assert(forceToBooleanType.IsBooleanType())
result = ApplyConversion(node, forceToBooleanType, result, isExplicit:=True, diagnostics:=diagnostics)
End If
Return result
End Function
''' <summary>
''' This helper is used to wrap nullable argument into something that would return null string if argument is null.
'''
''' Unlike conversion to a string where nullable nulls result in an exception,
''' concatenation requires that nullable nulls are treated as null strings.
''' Note that conversion is treated as explicit conversion.
''' </summary>
Private Function ForceLiftToEmptyString(left As BoundExpression, stringType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression
Debug.Assert(stringType.IsStringType)
Dim nothingStr = New BoundLiteral(left.Syntax, ConstantValue.Nothing, stringType).MakeCompilerGenerated()
Return AnalyzeConversionAndCreateBinaryConditionalExpression(left.Syntax,
left,
nothingStr,
Nothing,
stringType,
False,
diagnostics,
explicitConversion:=True).MakeCompilerGenerated()
End Function
Private Function BindUserDefinedNonShortCircuitingBinaryOperator(
node As SyntaxNode,
opKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
<[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedBinaryOperator
Debug.Assert(userDefinedOperator.Candidates.Length > 0)
opKind = opKind Or BinaryOperatorKind.UserDefined
Dim result As BoundExpression
If userDefinedOperator.BestResult.HasValue Then
Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value
result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(left, right),
bestCandidate,
userDefinedOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics)
If bestCandidate.Candidate.IsLifted Then
opKind = opKind Or BinaryOperatorKind.Lifted
End If
Else
result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good,
ImmutableArray.Create(Of BoundExpression)(left, right),
Nothing, userDefinedOperator, diagnostics,
callerInfoOpt:=Nothing)
End If
Return New BoundUserDefinedBinaryOperator(node, opKind, result, CheckOverflow, result.Type)
End Function
''' <summary>
''' This function builds a bound tree representing an overloaded short circuiting expression
''' after determining that the necessary semantic conditions are met.
'''
''' An expression of the form:
'''
''' x AndAlso y (where the type of x is X and the type of y is Y)
'''
''' is an overloaded short circuit operation if X and Y are user-defined types and an
''' applicable operator And exists after applying normal operator resolution rules.
'''
''' Given an applicable And operator declared in type T, the following must be true:
'''
''' - The return type and parameter types must be T.
''' - T must contain a declaration of operator IsFalse.
'''
''' If these conditions are met, the expression "x AndAlso y" is translated into:
'''
''' !T.IsFalse(temp = x) ? T.And(temp, y) : temp
'''
''' The temporary is necessary for evaluating x only once. Similarly, "x OrElse y" is
''' translated into:
'''
''' !T.IsTrue(temp = x) ? T.Or(temp, y) : temp
''' </summary>
Private Function BindUserDefinedShortCircuitingOperator(
node As SyntaxNode,
opKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
<[In]> ByRef bitwiseOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedShortCircuitingOperator
Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse)
Debug.Assert(bitwiseOperator.Candidates.Length > 0)
Dim bitwiseKind As BinaryOperatorKind = If(opKind = BinaryOperatorKind.AndAlso, BinaryOperatorKind.And, BinaryOperatorKind.Or) Or BinaryOperatorKind.UserDefined
Dim operatorType As TypeSymbol
Dim leftOperand As BoundExpression = Nothing
Dim leftPlaceholder As BoundRValuePlaceholder = Nothing
Dim test As BoundExpression = Nothing
Dim bitwise As BoundUserDefinedBinaryOperator
Dim hasErrors As Boolean = False
If Not bitwiseOperator.BestResult.HasValue Then
' This will take care of the diagnostic.
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics)
operatorType = bitwise.Type
hasErrors = True
GoTo Done
End If
Dim bitwiseAnalysis As OverloadResolution.CandidateAnalysisResult = bitwiseOperator.BestResult.Value
Dim bitwiseCandidate As OverloadResolution.Candidate = bitwiseAnalysis.Candidate
operatorType = bitwiseCandidate.ReturnType
If bitwiseCandidate.IsLifted Then
bitwiseKind = bitwiseKind Or BinaryOperatorKind.Lifted
End If
If Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(0).Type) OrElse
Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(1).Type) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_UnacceptableLogicalOperator3,
bitwiseCandidate.UnderlyingSymbol,
bitwiseCandidate.UnderlyingSymbol.ContainingType,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso,
SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)))
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator,
BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics.
hasErrors = True
GoTo Done
End If
leftPlaceholder = New BoundRValuePlaceholder(left.Syntax, operatorType).MakeCompilerGenerated()
' Find IsTrue/IsFalse operator
Dim leftCheckOperator As OverloadResolution.OverloadResolutionResult
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If opKind = BinaryOperatorKind.AndAlso Then
leftCheckOperator = OverloadResolution.ResolveIsFalseOperator(leftPlaceholder, Me, useSiteInfo)
Else
leftCheckOperator = OverloadResolution.ResolveIsTrueOperator(leftPlaceholder, Me, useSiteInfo)
End If
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If Not leftCheckOperator.BestResult.HasValue Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_ConditionOperatorRequired3,
operatorType,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword)),
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)))
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator,
BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics.
leftPlaceholder = Nothing
hasErrors = True
GoTo Done
End If
Dim checkCandidate As OverloadResolution.Candidate = leftCheckOperator.BestResult.Value.Candidate
Debug.Assert(checkCandidate.ReturnType.IsBooleanType() OrElse checkCandidate.ReturnType.IsNullableOfBoolean())
If Not operatorType.IsSameTypeIgnoringAll(checkCandidate.Parameters(0).Type) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_BinaryOperands3,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)),
left.Type, right.Type)
hasErrors = True
diagnostics = BindingDiagnosticBag.Discarded ' Ignore any additional diagnostics.
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics)
Else
' Convert the operands to the operator type.
Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) =
PassArguments(node, bitwiseAnalysis, ImmutableArray.Create(Of BoundExpression)(left, right), diagnostics)
Debug.Assert(argumentInfo.DefaultArguments.IsNull)
bitwiseAnalysis.ConversionsOpt = Nothing
bitwise = New BoundUserDefinedBinaryOperator(node, bitwiseKind,
CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bitwiseCandidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(leftPlaceholder, argumentInfo.Arguments(1)),
bitwiseAnalysis,
bitwiseOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics),
CheckOverflow,
operatorType)
leftOperand = argumentInfo.Arguments(0)
End If
Dim testOp As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node,
If(opKind = BinaryOperatorKind.AndAlso,
UnaryOperatorKind.IsFalse,
UnaryOperatorKind.IsTrue),
leftPlaceholder,
leftCheckOperator,
diagnostics).MakeCompilerGenerated()
testOp.UnderlyingExpression.SetWasCompilerGenerated()
If hasErrors Then
leftPlaceholder = Nothing
End If
If checkCandidate.IsLifted Then
test = ApplyNullableIsTrueOperator(testOp, checkCandidate.ReturnType.GetNullableUnderlyingTypeOrSelf())
Else
test = testOp
End If
Done:
Debug.Assert(hasErrors OrElse (leftOperand IsNot Nothing AndAlso leftPlaceholder IsNot Nothing AndAlso test IsNot Nothing))
Debug.Assert(Not hasErrors OrElse (leftOperand Is Nothing AndAlso leftPlaceholder Is Nothing))
bitwise.UnderlyingExpression.SetWasCompilerGenerated()
bitwise.SetWasCompilerGenerated()
Return New BoundUserDefinedShortCircuitingOperator(node, leftOperand, leftPlaceholder, test, bitwise, operatorType, hasErrors)
End Function
Private Shared Sub ReportBinaryOperatorOnObject(
operatorTokenKind As SyntaxKind,
operand As BoundExpression,
preliminaryOperatorKind As BinaryOperatorKind,
diagnostics As BindingDiagnosticBag
)
ReportDiagnostic(diagnostics, operand.Syntax,
ErrorFactory.ErrorInfo(
If(preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals,
ERRID.ERR_StrictDisallowsObjectComparison1, ERRID.ERR_StrictDisallowsObjectOperand1),
operatorTokenKind))
End Sub
''' <summary>
''' Returns Symbol for String type.
''' </summary>
Private Function SubstituteDBNullWithNothingString(
ByRef dbNullOperand As BoundExpression,
otherOperandType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As TypeSymbol
Dim stringType As TypeSymbol
If otherOperandType.IsStringType() Then
stringType = otherOperandType
Else
stringType = GetSpecialType(SpecialType.System_String, dbNullOperand.Syntax, diagnostics)
End If
dbNullOperand = New BoundConversion(dbNullOperand.Syntax, dbNullOperand, ConversionKind.Widening,
checked:=False, explicitCastInCode:=False, type:=stringType,
constantValueOpt:=ConstantValue.Nothing)
Return stringType
End Function
''' <summary>
''' Get symbol for a special type, reuse symbols for operand types to avoid type
''' lookups and construction of new instances of symbols.
''' </summary>
Private Function GetSpecialTypeForBinaryOperator(
node As SyntaxNode,
leftType As TypeSymbol,
rightType As TypeSymbol,
specialType As SpecialType,
makeNullable As Boolean,
diagnostics As BindingDiagnosticBag
) As TypeSymbol
Debug.Assert(specialType <> Microsoft.CodeAnalysis.SpecialType.None)
Debug.Assert(Not makeNullable OrElse leftType.IsNullableType() OrElse rightType.IsNullableType())
Dim resultType As TypeSymbol
Dim leftNullableUnderlying = leftType.GetNullableUnderlyingTypeOrSelf()
Dim leftSpecialType = leftNullableUnderlying.SpecialType
Dim rightNullableUnderlying = rightType.GetNullableUnderlyingTypeOrSelf()
Dim rightSpecialType = rightNullableUnderlying.SpecialType
If leftSpecialType = specialType Then
If Not makeNullable Then
resultType = leftNullableUnderlying
ElseIf leftType.IsNullableType() Then
resultType = leftType
ElseIf rightSpecialType = specialType Then
Debug.Assert(makeNullable AndAlso rightType.IsNullableType())
resultType = rightType
Else
Debug.Assert(makeNullable AndAlso
rightType.IsNullableType() AndAlso
Not leftType.IsNullableType())
resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(leftType)
End If
ElseIf rightSpecialType = specialType Then
If Not makeNullable Then
resultType = rightNullableUnderlying
ElseIf rightType.IsNullableType() Then
resultType = rightType
Else
Debug.Assert(makeNullable AndAlso
Not rightType.IsNullableType() AndAlso
leftType.IsNullableType())
resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(rightNullableUnderlying)
End If
Else
resultType = GetSpecialType(specialType, node, diagnostics)
If makeNullable Then
If leftType.IsNullableType() Then
resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
Else
Debug.Assert(rightType.IsNullableType())
resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
End If
End If
End If
Return resultType
End Function
''' <summary>
''' Get symbol for a Nullable type of particular type, reuse symbols for operand types to avoid type
''' lookups and construction of new instances of symbols.
''' </summary>
Private Shared Function GetNullableTypeForBinaryOperator(
leftType As TypeSymbol,
rightType As TypeSymbol,
ofType As TypeSymbol
) As TypeSymbol
Dim leftIsNullable = leftType.IsNullableType()
Dim rightIsNullable = rightType.IsNullableType()
Dim ofSpecialType = ofType.SpecialType
Debug.Assert(leftIsNullable OrElse rightIsNullable)
If ofSpecialType <> SpecialType.None Then
If leftIsNullable AndAlso leftType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then
Return leftType
ElseIf rightIsNullable AndAlso rightType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then
Return rightType
End If
End If
If leftIsNullable Then
Return DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(ofType)
Else
Return DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(ofType)
End If
End Function
Private Shared Function IsKnownToBeNullableNothing(expr As BoundExpression) As Boolean
Dim cast = expr
' TODO: Add handling for TryCast, similar to DirectCast
While cast.Kind = BoundKind.Conversion OrElse cast.Kind = BoundKind.DirectCast
If cast.HasErrors Then
Return False
End If
Dim resultType As TypeSymbol = Nothing
Select Case cast.Kind
Case BoundKind.Conversion
Dim conv = DirectCast(cast, BoundConversion)
resultType = conv.Type
cast = conv.Operand
Case BoundKind.DirectCast
Dim conv = DirectCast(cast, BoundDirectCast)
resultType = conv.Type
cast = conv.Operand
End Select
If resultType Is Nothing OrElse Not (resultType.IsNullableType() OrElse resultType.IsObjectType()) Then
Return False
End If
End While
Return cast.IsNothingLiteral()
End Function
Private Sub ReportUndefinedOperatorError(
syntax As SyntaxNode,
left As BoundExpression,
right As BoundExpression,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
diagnostics As BindingDiagnosticBag
)
Dim leftType = left.Type
Dim rightType = right.Type
Debug.Assert(leftType IsNot Nothing)
Debug.Assert(rightType IsNot Nothing)
If leftType.IsErrorType() OrElse rightType.IsErrorType() Then
Return ' Let's not report more errors.
End If
Dim operatorTokenText = SyntaxFacts.GetText(operatorTokenKind)
If OverloadResolution.UseUserDefinedBinaryOperators(operatorKind, leftType, rightType) AndAlso
Not leftType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso Not rightType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
(operatorKind = BinaryOperatorKind.Equals OrElse operatorKind = BinaryOperatorKind.NotEquals) AndAlso
leftType.IsReferenceType() AndAlso rightType.IsReferenceType() Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReferenceComparison3, operatorTokenText, leftType, rightType)
ElseIf IsIEnumerableOfXElement(leftType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, leftType)
ElseIf IsIEnumerableOfXElement(rightType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, rightType)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperands3, operatorTokenText, leftType, rightType)
End If
End Sub
''' <summary>
''' §11.12.2 Object Operands
''' The value Nothing is treated as the default value of the type of
''' the other operand in a binary operator expression. In a unary operator expression,
''' or if both operands are Nothing in a binary operator expression,
''' the type of the operation is Integer or the only result type of the operator,
''' if the operator does not result in Integer.
''' </summary>
Private Sub ConvertNothingLiterals(
operatorKind As BinaryOperatorKind,
ByRef left As BoundExpression,
ByRef right As BoundExpression,
diagnostics As BindingDiagnosticBag
)
Debug.Assert((operatorKind And BinaryOperatorKind.OpMask) = operatorKind AndAlso operatorKind <> 0)
Dim rightType As TypeSymbol
Dim leftType As TypeSymbol
If left.IsNothingLiteral() Then
If right.IsNothingLiteral() Then
' Both are NOTHING
Dim defaultRightSpecialType As SpecialType
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
defaultRightSpecialType = SpecialType.System_String
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso
defaultRightSpecialType = SpecialType.System_Boolean
Case BinaryOperatorKind.Add,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Subtract,
BinaryOperatorKind.Multiply,
BinaryOperatorKind.Power,
BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And
defaultRightSpecialType = SpecialType.System_Int32
Case Else
Throw ExceptionUtilities.UnexpectedValue(operatorKind)
End Select
rightType = GetSpecialType(defaultRightSpecialType, right.Syntax, diagnostics)
right = ApplyImplicitConversion(right.Syntax,
rightType,
right, diagnostics)
Else
rightType = right.Type
If rightType Is Nothing Then
Return
End If
End If
Debug.Assert(rightType IsNot Nothing)
Dim defaultLeftSpecialType As SpecialType = SpecialType.None
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
If rightType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse
rightType.IsCharSZArray() OrElse
rightType.IsDBNullType() Then
' For & and Like, a Nothing operand is typed String unless the other operand
' is non-intrinsic (VSW#240203).
' The same goes for DBNull (VSW#278518)
' The same goes for enum types (VSW#288077)
defaultLeftSpecialType = SpecialType.System_String
End If
Case BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift
' Nothing should default to Integer for Shift operations.
defaultLeftSpecialType = SpecialType.System_Int32
End Select
If defaultLeftSpecialType = SpecialType.None OrElse defaultLeftSpecialType = rightType.SpecialType Then
leftType = rightType
Else
leftType = GetSpecialType(defaultLeftSpecialType, left.Syntax, diagnostics)
End If
left = ApplyImplicitConversion(left.Syntax,
leftType,
left, diagnostics)
ElseIf right.IsNothingLiteral() Then
leftType = left.Type
If leftType Is Nothing Then
Return
End If
rightType = leftType
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
If leftType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse
leftType.IsCharSZArray() OrElse
leftType.IsDBNullType() Then
' For & and Like, a Nothing operand is typed String unless the other operand
' is non-intrinsic (VSW#240203).
' The same goes for DBNull (VSW#278518)
' The same goes for enum types (VSW#288077)
If leftType.SpecialType <> SpecialType.System_String Then
rightType = GetSpecialType(SpecialType.System_String, right.Syntax, diagnostics)
End If
End If
End Select
right = ApplyImplicitConversion(right.Syntax,
rightType,
right, diagnostics)
End If
End Sub
Private Function BindUnaryOperator(node As UnaryExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim operand As BoundExpression = BindValue(node.Operand, diagnostics)
Dim preliminaryOperatorKind As UnaryOperatorKind = OverloadResolution.MapUnaryOperatorKind(node.Kind)
If Not operand.HasErrors AndAlso operand.IsNothingLiteral Then
'§11.12.2 Object Operands
'In a unary operator expression, or if both operands are Nothing in a
'binary operator expression, the type of the operation is Integer
Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.Operand, diagnostics)
operand = ApplyImplicitConversion(node.Operand, int32Type, operand, diagnostics)
Else
operand = MakeRValue(operand, diagnostics)
End If
If operand.HasErrors Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
diagnostics = BindingDiagnosticBag.Discarded
End If
Dim intrinsicOperatorType As SpecialType = SpecialType.None
Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim operatorKind As UnaryOperatorKind = OverloadResolution.ResolveUnaryOperator(preliminaryOperatorKind, operand, Me, intrinsicOperatorType, userDefinedOperator, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If operatorKind = UnaryOperatorKind.UserDefined Then
Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue,
userDefinedOperator.BestResult.Value.Candidate,
Nothing)
If bestCandidate Is Nothing OrElse
Not bestCandidate.IsLifted OrElse
(OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then
Return BindUserDefinedUnaryOperator(node, preliminaryOperatorKind, operand, userDefinedOperator, diagnostics)
End If
operatorKind = UnaryOperatorKind.Error
End If
If operatorKind = UnaryOperatorKind.Error Then
ReportUndefinedOperatorError(node, operand, diagnostics)
Return New BoundUnaryOperator(node, preliminaryOperatorKind Or UnaryOperatorKind.Error, operand, CheckOverflow, ErrorTypeSymbol.UnknownResultType, HasErrors:=True)
End If
' We are dealing with intrinsic operator
Dim operandType As TypeSymbol = operand.Type
Dim resultType As TypeSymbol = Nothing
If intrinsicOperatorType = SpecialType.None Then
Debug.Assert(operandType.GetNullableUnderlyingTypeOrSelf().IsEnumType())
resultType = operandType
Else
If operandType.GetNullableUnderlyingTypeOrSelf().SpecialType = intrinsicOperatorType Then
resultType = operandType
Else
resultType = GetSpecialType(intrinsicOperatorType, node.Operand, diagnostics)
If operandType.IsNullableType() Then
resultType = DirectCast(operandType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
End If
End If
End If
Debug.Assert(((operatorKind And UnaryOperatorKind.Lifted) <> 0) = resultType.IsNullableType())
' Option Strict disallows all unary operations on Object operands. Otherwise just warn.
If operandType.SpecialType = SpecialType.System_Object Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.ERR_StrictDisallowsObjectOperand1, node.OperatorToken))
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectMath2, node.OperatorToken))
End If
End If
operand = ApplyImplicitConversion(node.Operand, resultType, operand, diagnostics)
Dim constantValue As ConstantValue = Nothing
If Not operand.HasErrors Then
Dim integerOverflow As Boolean = False
constantValue = OverloadResolution.TryFoldConstantUnaryOperator(operatorKind, operand, resultType, integerOverflow)
' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior.
If constantValue IsNot Nothing AndAlso (constantValue.IsBad OrElse integerOverflow) Then
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, resultType))
' there should be no constant value in case of overflows.
If Not constantValue.IsBad Then
constantValue = constantValue.Bad
End If
End If
End If
Return New BoundUnaryOperator(node, operatorKind, operand, CheckOverflow, constantValue, resultType)
End Function
Private Function BindUserDefinedUnaryOperator(
node As SyntaxNode,
opKind As UnaryOperatorKind,
operand As BoundExpression,
<[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedUnaryOperator
Debug.Assert(userDefinedOperator.Candidates.Length > 0)
Dim result As BoundExpression
opKind = opKind Or UnaryOperatorKind.UserDefined
If userDefinedOperator.BestResult.HasValue Then
Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value
result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(operand),
bestCandidate,
userDefinedOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics)
If bestCandidate.Candidate.IsLifted Then
opKind = opKind Or UnaryOperatorKind.Lifted
End If
Else
result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good,
ImmutableArray.Create(Of BoundExpression)(operand),
Nothing, userDefinedOperator, diagnostics,
callerInfoOpt:=Nothing)
End If
Return New BoundUserDefinedUnaryOperator(node, opKind, result, result.Type)
End Function
Private Shared Sub ReportUndefinedOperatorError(
syntax As UnaryExpressionSyntax,
operand As BoundExpression,
diagnostics As BindingDiagnosticBag
)
If operand.Type.IsErrorType() Then
Return ' Let's not report more errors.
End If
ReportDiagnostic(diagnostics, syntax, ErrorFactory.ErrorInfo(ERRID.ERR_UnaryOperand2, syntax.OperatorToken, operand.Type))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
' Binding of binary and unary operators is implemented in this part.
Partial Friend Class Binder
Private Function BindIsExpression(
node As BinaryExpressionSyntax,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Debug.Assert(node.Kind = SyntaxKind.IsExpression OrElse node.Kind = SyntaxKind.IsNotExpression)
Dim [isNot] As Boolean = (node.Kind = SyntaxKind.IsNotExpression)
' The function below will make sure they are RValues.
Dim left As BoundExpression = BindExpression(node.Left, diagnostics)
Dim right As BoundExpression = BindExpression(node.Right, diagnostics)
Return BindIsExpression(left, right, node, [isNot], diagnostics)
End Function
Private Function BindIsExpression(
left As BoundExpression,
right As BoundExpression,
node As SyntaxNode,
[isNot] As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
left = MakeRValue(left, diagnostics)
right = MakeRValue(right, diagnostics)
left = ValidateAndConvertIsExpressionArgument(left, right, [isNot], diagnostics)
right = ValidateAndConvertIsExpressionArgument(right, left, [isNot], diagnostics)
Dim result As BoundExpression
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, node, diagnostics)
result = New BoundBinaryOperator(node,
If([isNot], BinaryOperatorKind.IsNot, BinaryOperatorKind.Is),
left,
right,
checked:=False,
type:=booleanType,
hasErrors:=booleanType.IsErrorType())
' TODO: Add rewrite for Nullable.
Return result
End Function
''' <summary>
''' Validate and apply appropriate conversion for the target argument of Is/IsNot expression.
''' </summary>
Private Function ValidateAndConvertIsExpressionArgument(
targetArgument As BoundExpression,
otherArgument As BoundExpression,
[isNot] As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim targetArgumentType As TypeSymbol = targetArgument.Type
Dim result As BoundExpression
If targetArgument.IsNothingLiteral() Then
result = targetArgument
ElseIf targetArgumentType.IsErrorType() Then
result = targetArgument
ElseIf targetArgumentType.IsReferenceType Then
result = ApplyImplicitConversion(targetArgument.Syntax,
GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics),
targetArgument,
diagnostics)
ElseIf targetArgumentType.IsNullableType() Then
If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOperatorNullable1, ERRID.ERR_IsOperatorNullable1),
targetArgumentType)
End If
result = targetArgument
ElseIf targetArgumentType.IsTypeParameter() AndAlso Not targetArgumentType.IsValueType Then
If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOperatorGenericParam1, ERRID.ERR_IsOperatorGenericParam1),
targetArgumentType)
End If
' If any of the left or right operands of the Is or IsNot operands
' are entities of type parameters types, then they need to be boxed.
result = ApplyImplicitConversion(targetArgument.Syntax,
GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics),
targetArgument,
diagnostics)
Else
ReportDiagnostic(diagnostics, targetArgument.Syntax,
If([isNot], ERRID.ERR_IsNotOpRequiresReferenceTypes1, ERRID.ERR_IsOperatorRequiresReferenceTypes1),
targetArgumentType)
result = targetArgument
End If
Return result
End Function
Private Function BindBinaryOperator(
node As BinaryExpressionSyntax,
isOperandOfConditionalBranch As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundExpression
' Some tools, such as ASP .NET, generate expressions containing thousands
' of string concatenations. For this reason, for string concatenations,
' avoid the usual recursion along the left side of the parse. Also, attempt
' to flatten whole sequences of string literal concatenations to avoid
' allocating space for intermediate results.
Dim preliminaryOperatorKind As BinaryOperatorKind = OverloadResolution.MapBinaryOperatorKind(node.Kind)
Dim propagateIsOperandOfConditionalBranch = isOperandOfConditionalBranch AndAlso
(preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse
preliminaryOperatorKind = BinaryOperatorKind.OrElse)
Dim binary As BinaryExpressionSyntax = node
Dim child As ExpressionSyntax
Do
child = binary.Left
Select Case child.Kind
Case SyntaxKind.AddExpression,
SyntaxKind.ConcatenateExpression,
SyntaxKind.LikeExpression,
SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.SubtractExpression,
SyntaxKind.MultiplyExpression,
SyntaxKind.ExponentiateExpression,
SyntaxKind.DivideExpression,
SyntaxKind.ModuloExpression,
SyntaxKind.IntegerDivideExpression,
SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression,
SyntaxKind.ExclusiveOrExpression,
SyntaxKind.OrExpression,
SyntaxKind.AndExpression
If propagateIsOperandOfConditionalBranch Then
Exit Do
End If
Case SyntaxKind.OrElseExpression,
SyntaxKind.AndAlsoExpression
Exit Select
Case Else
Exit Do
End Select
binary = DirectCast(child, BinaryExpressionSyntax)
Loop
Dim left As BoundExpression = BindValue(child, diagnostics, propagateIsOperandOfConditionalBranch)
Do
binary = DirectCast(child.Parent, BinaryExpressionSyntax)
Dim right As BoundExpression = BindValue(binary.Right, diagnostics, propagateIsOperandOfConditionalBranch)
left = BindBinaryOperator(binary, left, right, binary.OperatorToken.Kind,
OverloadResolution.MapBinaryOperatorKind(binary.Kind),
If(binary Is node, isOperandOfConditionalBranch, propagateIsOperandOfConditionalBranch),
diagnostics)
child = binary
Loop While child IsNot node
Return left
End Function
Private Function BindBinaryOperator(
node As SyntaxNode,
left As BoundExpression,
right As BoundExpression,
operatorTokenKind As SyntaxKind,
preliminaryOperatorKind As BinaryOperatorKind,
isOperandOfConditionalBranch As Boolean,
diagnostics As BindingDiagnosticBag,
Optional isSelectCase As Boolean = False
) As BoundExpression
Debug.Assert(left.IsValue)
Debug.Assert(right.IsValue)
Dim originalDiagnostics = diagnostics
If (left.HasErrors OrElse right.HasErrors) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
diagnostics = BindingDiagnosticBag.Discarded
End If
' Deal with NOTHING literal as an input.
ConvertNothingLiterals(preliminaryOperatorKind, left, right, diagnostics)
left = MakeRValue(left, diagnostics)
right = MakeRValue(right, diagnostics)
If (left.HasErrors OrElse right.HasErrors) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim leftType As TypeSymbol = left.Type
Dim rightType As TypeSymbol = right.Type
Dim leftIsDBNull As Boolean = leftType.IsDBNullType()
Dim rightIsDBNull As Boolean = rightType.IsDBNullType()
'§11.16 Concatenation Operator
'A System.DBNull value is converted to the literal Nothing typed as String.
If (preliminaryOperatorKind = BinaryOperatorKind.Concatenate AndAlso leftIsDBNull <> rightIsDBNull) OrElse
(preliminaryOperatorKind = BinaryOperatorKind.Add AndAlso
((leftType.IsStringType() AndAlso rightIsDBNull) OrElse (leftIsDBNull AndAlso rightType.IsStringType))) Then
Debug.Assert(leftIsDBNull Xor rightIsDBNull)
If leftIsDBNull Then
leftType = SubstituteDBNullWithNothingString(left, rightType, diagnostics)
Else
rightType = SubstituteDBNullWithNothingString(right, leftType, diagnostics)
End If
End If
' For comparison operators, the result type computed here is not
' the result type of the comparison (which is typically boolean),
' but is the type to which the operands are to be converted. For
' other operators, the type computed here is both the result type
' and the common operand type.
Dim intrinsicOperatorType As SpecialType = SpecialType.None
Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim operatorKind As BinaryOperatorKind = OverloadResolution.ResolveBinaryOperator(preliminaryOperatorKind, left, right, Me,
True,
intrinsicOperatorType,
userDefinedOperator,
useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If operatorKind = BinaryOperatorKind.UserDefined Then
Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue,
userDefinedOperator.BestResult.Value.Candidate,
Nothing)
If bestCandidate Is Nothing OrElse
Not bestCandidate.IsLifted OrElse
(OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(1).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then
If preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse Then
Return BindUserDefinedShortCircuitingOperator(node, preliminaryOperatorKind, left, right,
userDefinedOperator, diagnostics)
Else
Return BindUserDefinedNonShortCircuitingBinaryOperator(node, preliminaryOperatorKind, left, right,
userDefinedOperator, diagnostics)
End If
End If
operatorKind = BinaryOperatorKind.Error
End If
If operatorKind = BinaryOperatorKind.Error Then
ReportUndefinedOperatorError(node, left, right, operatorTokenKind, preliminaryOperatorKind, diagnostics)
Return New BoundBinaryOperator(node, preliminaryOperatorKind Or BinaryOperatorKind.Error, left, right, CheckOverflow, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
' We are dealing with intrinsic operator
' Get the symbol for operand type
Dim operandType As TypeSymbol
If intrinsicOperatorType = SpecialType.None Then
' Must be a bitwise operation with enum type.
Debug.Assert(leftType.GetNullableUnderlyingTypeOrSelf().IsEnumType() AndAlso
leftType.GetNullableUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(rightType.GetNullableUnderlyingTypeOrSelf()))
If (operatorKind And BinaryOperatorKind.Lifted) = 0 OrElse leftType.IsNullableType() Then
operandType = leftType
Else
Debug.Assert(rightType.IsNullableType())
operandType = rightType
End If
Else
operandType = GetSpecialTypeForBinaryOperator(node, leftType, rightType, intrinsicOperatorType,
(operatorKind And BinaryOperatorKind.Lifted) <> 0, diagnostics)
End If
' Get the symbol for result type
Dim operatorResultType As TypeSymbol = operandType
Dim forceToBooleanType As TypeSymbol = Nothing
Select Case preliminaryOperatorKind
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Like
If OptionCompareText AndAlso (operandType.IsObjectType() OrElse operandType.IsStringType()) Then
operatorKind = operatorKind Or BinaryOperatorKind.CompareText
End If
If Not operatorResultType.IsObjectType() OrElse
(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) Then
Dim booleanType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Boolean,
False, diagnostics)
If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then
operatorResultType = GetNullableTypeForBinaryOperator(leftType, rightType, booleanType)
If (preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals) AndAlso
(IsKnownToBeNullableNothing(left) OrElse IsKnownToBeNullableNothing(right)) Then
ReportDiagnostic(diagnostics, node,
ErrorFactory.ErrorInfo(
If(preliminaryOperatorKind = BinaryOperatorKind.Equals,
ERRID.WRN_EqualToLiteralNothing, ERRID.WRN_NotEqualToLiteralNothing)))
End If
Else
If Not operatorResultType.IsObjectType() Then
operatorResultType = booleanType
Else
' I believe this is just an optimization to prevent Object from bubbling up the tree.
Debug.Assert(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like)
forceToBooleanType = booleanType
End If
End If
End If
End Select
If operandType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse
operatorResultType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse
(forceToBooleanType IsNot Nothing AndAlso forceToBooleanType.GetNullableUnderlyingTypeOrSelf().IsErrorType()) Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim hasError As Boolean = False
' Option Strict disallows all operations on Object operands. Or, at least, warn.
If OptionStrict = VisualBasic.OptionStrict.On Then
Dim reportedAnEror As Boolean = False
If leftType.IsObjectType Then
ReportBinaryOperatorOnObject(operatorTokenKind, left, preliminaryOperatorKind, diagnostics)
reportedAnEror = True
End If
If rightType.IsObjectType() Then
ReportBinaryOperatorOnObject(operatorTokenKind, right, preliminaryOperatorKind, diagnostics)
reportedAnEror = True
End If
If reportedAnEror Then
hasError = True
' Suppress any additional diagnostics by overriding DiagnosticBag.
If diagnostics Is originalDiagnostics Then
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then 'warn if option strict is off
If Not isSelectCase OrElse preliminaryOperatorKind <> BinaryOperatorKind.OrElse Then
Dim errorId = If(isSelectCase, ERRID.WRN_ObjectMathSelectCase,
If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_ObjectMath1,
If(preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.WRN_ObjectMath1Not, ERRID.WRN_ObjectMath2)))
If leftType.IsObjectType Then
ReportDiagnostic(diagnostics, left.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind))
End If
If rightType.IsObjectType Then
ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind))
End If
End If
End If
' Apply conversions to operands.
Dim explicitSemanticForConcatArgument As Boolean = False
' Concatenation will apply conversions to its operands as if the
' conversions were explicit. Effectively, the use of the concatenation
' operator is treated as an explicit conversion to String.
If preliminaryOperatorKind = BinaryOperatorKind.Concatenate Then
explicitSemanticForConcatArgument = True
Debug.Assert((operatorKind And BinaryOperatorKind.Lifted) = 0)
If operandType.IsStringType() Then
If left.Type.IsNullableType Then
left = ForceLiftToEmptyString(left, operandType, diagnostics)
End If
If right.Type.IsNullableType Then
right = ForceLiftToEmptyString(right, operandType, diagnostics)
End If
End If
End If
Dim beforeConversion As BoundExpression = left
left = ApplyConversion(left.Syntax, operandType, left, explicitSemanticForConcatArgument, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
If explicitSemanticForConcatArgument AndAlso left IsNot beforeConversion AndAlso left.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(left, BoundConversion)
left = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False,
constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt,
type:=conversion.Type)
End If
If (preliminaryOperatorKind = BinaryOperatorKind.LeftShift OrElse preliminaryOperatorKind = BinaryOperatorKind.RightShift) AndAlso
Not operandType.IsObjectType() Then
Dim rightTargetType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Int32,
False, diagnostics)
'§11.18 Shift Operators
'The type of the right operand must be implicitly convertible to Integer
' If operator is lifted, convert right operand to Nullable(Of Integer)
If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then
rightTargetType = GetNullableTypeForBinaryOperator(leftType, rightType, rightTargetType)
End If
right = ApplyImplicitConversion(right.Syntax, rightTargetType, right, diagnostics)
Else
beforeConversion = right
right = ApplyConversion(right.Syntax, operandType, right, explicitSemanticForConcatArgument, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
If explicitSemanticForConcatArgument AndAlso right IsNot beforeConversion AndAlso right.Kind = BoundKind.Conversion Then
Dim conversion = DirectCast(right, BoundConversion)
right = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False,
constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt,
type:=conversion.Type)
End If
End If
If (operatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Add AndAlso operatorResultType.IsStringType() Then
' Transform the addition into a string concatenation. This won't use a runtime helper - it will turn into System.String::Concat
operatorKind = (operatorKind And (Not BinaryOperatorKind.OpMask))
operatorKind = operatorKind Or BinaryOperatorKind.Concatenate
End If
' Perform constant folding.
Dim value As ConstantValue = Nothing
If Not (left.HasErrors OrElse right.HasErrors) Then
Dim integerOverflow As Boolean = False
Dim divideByZero As Boolean = False
Dim lengthOutOfLimit As Boolean = False
value = OverloadResolution.TryFoldConstantBinaryOperator(operatorKind,
left,
right,
operatorResultType,
integerOverflow,
divideByZero,
lengthOutOfLimit)
If value IsNot Nothing Then
If divideByZero Then
Debug.Assert(value.IsBad)
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ZeroDivide))
ElseIf lengthOutOfLimit Then
Debug.Assert(value.IsBad)
ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(ERRID.ERR_ConstantStringTooLong))
ElseIf (value.IsBad OrElse integerOverflow) Then
' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior.
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, operatorResultType))
' there should be no constant value in case of overflows.
If Not value.IsBad Then
value = ConstantValue.Bad
End If
End If
End If
End If
Dim result As BoundExpression = New BoundBinaryOperator(node, operatorKind Or If(isOperandOfConditionalBranch, BinaryOperatorKind.IsOperandOfConditionalBranch, Nothing),
left, right, CheckOverflow, value, operatorResultType, hasError)
If forceToBooleanType IsNot Nothing Then
Debug.Assert(forceToBooleanType.IsBooleanType())
result = ApplyConversion(node, forceToBooleanType, result, isExplicit:=True, diagnostics:=diagnostics)
End If
Return result
End Function
''' <summary>
''' This helper is used to wrap nullable argument into something that would return null string if argument is null.
'''
''' Unlike conversion to a string where nullable nulls result in an exception,
''' concatenation requires that nullable nulls are treated as null strings.
''' Note that conversion is treated as explicit conversion.
''' </summary>
Private Function ForceLiftToEmptyString(left As BoundExpression, stringType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression
Debug.Assert(stringType.IsStringType)
Dim nothingStr = New BoundLiteral(left.Syntax, ConstantValue.Nothing, stringType).MakeCompilerGenerated()
Return AnalyzeConversionAndCreateBinaryConditionalExpression(left.Syntax,
left,
nothingStr,
Nothing,
stringType,
False,
diagnostics,
explicitConversion:=True).MakeCompilerGenerated()
End Function
Private Function BindUserDefinedNonShortCircuitingBinaryOperator(
node As SyntaxNode,
opKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
<[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedBinaryOperator
Debug.Assert(userDefinedOperator.Candidates.Length > 0)
opKind = opKind Or BinaryOperatorKind.UserDefined
Dim result As BoundExpression
If userDefinedOperator.BestResult.HasValue Then
Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value
result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(left, right),
bestCandidate,
userDefinedOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics)
If bestCandidate.Candidate.IsLifted Then
opKind = opKind Or BinaryOperatorKind.Lifted
End If
Else
result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good,
ImmutableArray.Create(Of BoundExpression)(left, right),
Nothing, userDefinedOperator, diagnostics,
callerInfoOpt:=Nothing)
End If
Return New BoundUserDefinedBinaryOperator(node, opKind, result, CheckOverflow, result.Type)
End Function
''' <summary>
''' This function builds a bound tree representing an overloaded short circuiting expression
''' after determining that the necessary semantic conditions are met.
'''
''' An expression of the form:
'''
''' x AndAlso y (where the type of x is X and the type of y is Y)
'''
''' is an overloaded short circuit operation if X and Y are user-defined types and an
''' applicable operator And exists after applying normal operator resolution rules.
'''
''' Given an applicable And operator declared in type T, the following must be true:
'''
''' - The return type and parameter types must be T.
''' - T must contain a declaration of operator IsFalse.
'''
''' If these conditions are met, the expression "x AndAlso y" is translated into:
'''
''' !T.IsFalse(temp = x) ? T.And(temp, y) : temp
'''
''' The temporary is necessary for evaluating x only once. Similarly, "x OrElse y" is
''' translated into:
'''
''' !T.IsTrue(temp = x) ? T.Or(temp, y) : temp
''' </summary>
Private Function BindUserDefinedShortCircuitingOperator(
node As SyntaxNode,
opKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
<[In]> ByRef bitwiseOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedShortCircuitingOperator
Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse)
Debug.Assert(bitwiseOperator.Candidates.Length > 0)
Dim bitwiseKind As BinaryOperatorKind = If(opKind = BinaryOperatorKind.AndAlso, BinaryOperatorKind.And, BinaryOperatorKind.Or) Or BinaryOperatorKind.UserDefined
Dim operatorType As TypeSymbol
Dim leftOperand As BoundExpression = Nothing
Dim leftPlaceholder As BoundRValuePlaceholder = Nothing
Dim test As BoundExpression = Nothing
Dim bitwise As BoundUserDefinedBinaryOperator
Dim hasErrors As Boolean = False
If Not bitwiseOperator.BestResult.HasValue Then
' This will take care of the diagnostic.
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics)
operatorType = bitwise.Type
hasErrors = True
GoTo Done
End If
Dim bitwiseAnalysis As OverloadResolution.CandidateAnalysisResult = bitwiseOperator.BestResult.Value
Dim bitwiseCandidate As OverloadResolution.Candidate = bitwiseAnalysis.Candidate
operatorType = bitwiseCandidate.ReturnType
If bitwiseCandidate.IsLifted Then
bitwiseKind = bitwiseKind Or BinaryOperatorKind.Lifted
End If
If Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(0).Type) OrElse
Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(1).Type) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_UnacceptableLogicalOperator3,
bitwiseCandidate.UnderlyingSymbol,
bitwiseCandidate.UnderlyingSymbol.ContainingType,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso,
SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)))
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator,
BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics.
hasErrors = True
GoTo Done
End If
leftPlaceholder = New BoundRValuePlaceholder(left.Syntax, operatorType).MakeCompilerGenerated()
' Find IsTrue/IsFalse operator
Dim leftCheckOperator As OverloadResolution.OverloadResolutionResult
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If opKind = BinaryOperatorKind.AndAlso Then
leftCheckOperator = OverloadResolution.ResolveIsFalseOperator(leftPlaceholder, Me, useSiteInfo)
Else
leftCheckOperator = OverloadResolution.ResolveIsTrueOperator(leftPlaceholder, Me, useSiteInfo)
End If
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If Not leftCheckOperator.BestResult.HasValue Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_ConditionOperatorRequired3,
operatorType,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword)),
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)))
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator,
BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics.
leftPlaceholder = Nothing
hasErrors = True
GoTo Done
End If
Dim checkCandidate As OverloadResolution.Candidate = leftCheckOperator.BestResult.Value.Candidate
Debug.Assert(checkCandidate.ReturnType.IsBooleanType() OrElse checkCandidate.ReturnType.IsNullableOfBoolean())
If Not operatorType.IsSameTypeIgnoringAll(checkCandidate.Parameters(0).Type) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_BinaryOperands3,
SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)),
left.Type, right.Type)
hasErrors = True
diagnostics = BindingDiagnosticBag.Discarded ' Ignore any additional diagnostics.
bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics)
Else
' Convert the operands to the operator type.
Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) =
PassArguments(node, bitwiseAnalysis, ImmutableArray.Create(Of BoundExpression)(left, right), diagnostics)
Debug.Assert(argumentInfo.DefaultArguments.IsNull)
bitwiseAnalysis.ConversionsOpt = Nothing
bitwise = New BoundUserDefinedBinaryOperator(node, bitwiseKind,
CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bitwiseCandidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(leftPlaceholder, argumentInfo.Arguments(1)),
bitwiseAnalysis,
bitwiseOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics),
CheckOverflow,
operatorType)
leftOperand = argumentInfo.Arguments(0)
End If
Dim testOp As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node,
If(opKind = BinaryOperatorKind.AndAlso,
UnaryOperatorKind.IsFalse,
UnaryOperatorKind.IsTrue),
leftPlaceholder,
leftCheckOperator,
diagnostics).MakeCompilerGenerated()
testOp.UnderlyingExpression.SetWasCompilerGenerated()
If hasErrors Then
leftPlaceholder = Nothing
End If
If checkCandidate.IsLifted Then
test = ApplyNullableIsTrueOperator(testOp, checkCandidate.ReturnType.GetNullableUnderlyingTypeOrSelf())
Else
test = testOp
End If
Done:
Debug.Assert(hasErrors OrElse (leftOperand IsNot Nothing AndAlso leftPlaceholder IsNot Nothing AndAlso test IsNot Nothing))
Debug.Assert(Not hasErrors OrElse (leftOperand Is Nothing AndAlso leftPlaceholder Is Nothing))
bitwise.UnderlyingExpression.SetWasCompilerGenerated()
bitwise.SetWasCompilerGenerated()
Return New BoundUserDefinedShortCircuitingOperator(node, leftOperand, leftPlaceholder, test, bitwise, operatorType, hasErrors)
End Function
Private Shared Sub ReportBinaryOperatorOnObject(
operatorTokenKind As SyntaxKind,
operand As BoundExpression,
preliminaryOperatorKind As BinaryOperatorKind,
diagnostics As BindingDiagnosticBag
)
ReportDiagnostic(diagnostics, operand.Syntax,
ErrorFactory.ErrorInfo(
If(preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals,
ERRID.ERR_StrictDisallowsObjectComparison1, ERRID.ERR_StrictDisallowsObjectOperand1),
operatorTokenKind))
End Sub
''' <summary>
''' Returns Symbol for String type.
''' </summary>
Private Function SubstituteDBNullWithNothingString(
ByRef dbNullOperand As BoundExpression,
otherOperandType As TypeSymbol,
diagnostics As BindingDiagnosticBag
) As TypeSymbol
Dim stringType As TypeSymbol
If otherOperandType.IsStringType() Then
stringType = otherOperandType
Else
stringType = GetSpecialType(SpecialType.System_String, dbNullOperand.Syntax, diagnostics)
End If
dbNullOperand = New BoundConversion(dbNullOperand.Syntax, dbNullOperand, ConversionKind.Widening,
checked:=False, explicitCastInCode:=False, type:=stringType,
constantValueOpt:=ConstantValue.Nothing)
Return stringType
End Function
''' <summary>
''' Get symbol for a special type, reuse symbols for operand types to avoid type
''' lookups and construction of new instances of symbols.
''' </summary>
Private Function GetSpecialTypeForBinaryOperator(
node As SyntaxNode,
leftType As TypeSymbol,
rightType As TypeSymbol,
specialType As SpecialType,
makeNullable As Boolean,
diagnostics As BindingDiagnosticBag
) As TypeSymbol
Debug.Assert(specialType <> Microsoft.CodeAnalysis.SpecialType.None)
Debug.Assert(Not makeNullable OrElse leftType.IsNullableType() OrElse rightType.IsNullableType())
Dim resultType As TypeSymbol
Dim leftNullableUnderlying = leftType.GetNullableUnderlyingTypeOrSelf()
Dim leftSpecialType = leftNullableUnderlying.SpecialType
Dim rightNullableUnderlying = rightType.GetNullableUnderlyingTypeOrSelf()
Dim rightSpecialType = rightNullableUnderlying.SpecialType
If leftSpecialType = specialType Then
If Not makeNullable Then
resultType = leftNullableUnderlying
ElseIf leftType.IsNullableType() Then
resultType = leftType
ElseIf rightSpecialType = specialType Then
Debug.Assert(makeNullable AndAlso rightType.IsNullableType())
resultType = rightType
Else
Debug.Assert(makeNullable AndAlso
rightType.IsNullableType() AndAlso
Not leftType.IsNullableType())
resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(leftType)
End If
ElseIf rightSpecialType = specialType Then
If Not makeNullable Then
resultType = rightNullableUnderlying
ElseIf rightType.IsNullableType() Then
resultType = rightType
Else
Debug.Assert(makeNullable AndAlso
Not rightType.IsNullableType() AndAlso
leftType.IsNullableType())
resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(rightNullableUnderlying)
End If
Else
resultType = GetSpecialType(specialType, node, diagnostics)
If makeNullable Then
If leftType.IsNullableType() Then
resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
Else
Debug.Assert(rightType.IsNullableType())
resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
End If
End If
End If
Return resultType
End Function
''' <summary>
''' Get symbol for a Nullable type of particular type, reuse symbols for operand types to avoid type
''' lookups and construction of new instances of symbols.
''' </summary>
Private Shared Function GetNullableTypeForBinaryOperator(
leftType As TypeSymbol,
rightType As TypeSymbol,
ofType As TypeSymbol
) As TypeSymbol
Dim leftIsNullable = leftType.IsNullableType()
Dim rightIsNullable = rightType.IsNullableType()
Dim ofSpecialType = ofType.SpecialType
Debug.Assert(leftIsNullable OrElse rightIsNullable)
If ofSpecialType <> SpecialType.None Then
If leftIsNullable AndAlso leftType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then
Return leftType
ElseIf rightIsNullable AndAlso rightType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then
Return rightType
End If
End If
If leftIsNullable Then
Return DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(ofType)
Else
Return DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(ofType)
End If
End Function
Private Shared Function IsKnownToBeNullableNothing(expr As BoundExpression) As Boolean
Dim cast = expr
' TODO: Add handling for TryCast, similar to DirectCast
While cast.Kind = BoundKind.Conversion OrElse cast.Kind = BoundKind.DirectCast
If cast.HasErrors Then
Return False
End If
Dim resultType As TypeSymbol = Nothing
Select Case cast.Kind
Case BoundKind.Conversion
Dim conv = DirectCast(cast, BoundConversion)
resultType = conv.Type
cast = conv.Operand
Case BoundKind.DirectCast
Dim conv = DirectCast(cast, BoundDirectCast)
resultType = conv.Type
cast = conv.Operand
End Select
If resultType Is Nothing OrElse Not (resultType.IsNullableType() OrElse resultType.IsObjectType()) Then
Return False
End If
End While
Return cast.IsNothingLiteral()
End Function
Private Sub ReportUndefinedOperatorError(
syntax As SyntaxNode,
left As BoundExpression,
right As BoundExpression,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
diagnostics As BindingDiagnosticBag
)
Dim leftType = left.Type
Dim rightType = right.Type
Debug.Assert(leftType IsNot Nothing)
Debug.Assert(rightType IsNot Nothing)
If leftType.IsErrorType() OrElse rightType.IsErrorType() Then
Return ' Let's not report more errors.
End If
Dim operatorTokenText = SyntaxFacts.GetText(operatorTokenKind)
If OverloadResolution.UseUserDefinedBinaryOperators(operatorKind, leftType, rightType) AndAlso
Not leftType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso Not rightType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
(operatorKind = BinaryOperatorKind.Equals OrElse operatorKind = BinaryOperatorKind.NotEquals) AndAlso
leftType.IsReferenceType() AndAlso rightType.IsReferenceType() Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReferenceComparison3, operatorTokenText, leftType, rightType)
ElseIf IsIEnumerableOfXElement(leftType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, leftType)
ElseIf IsIEnumerableOfXElement(rightType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, rightType)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperands3, operatorTokenText, leftType, rightType)
End If
End Sub
''' <summary>
''' §11.12.2 Object Operands
''' The value Nothing is treated as the default value of the type of
''' the other operand in a binary operator expression. In a unary operator expression,
''' or if both operands are Nothing in a binary operator expression,
''' the type of the operation is Integer or the only result type of the operator,
''' if the operator does not result in Integer.
''' </summary>
Private Sub ConvertNothingLiterals(
operatorKind As BinaryOperatorKind,
ByRef left As BoundExpression,
ByRef right As BoundExpression,
diagnostics As BindingDiagnosticBag
)
Debug.Assert((operatorKind And BinaryOperatorKind.OpMask) = operatorKind AndAlso operatorKind <> 0)
Dim rightType As TypeSymbol
Dim leftType As TypeSymbol
If left.IsNothingLiteral() Then
If right.IsNothingLiteral() Then
' Both are NOTHING
Dim defaultRightSpecialType As SpecialType
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
defaultRightSpecialType = SpecialType.System_String
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso
defaultRightSpecialType = SpecialType.System_Boolean
Case BinaryOperatorKind.Add,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Subtract,
BinaryOperatorKind.Multiply,
BinaryOperatorKind.Power,
BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And
defaultRightSpecialType = SpecialType.System_Int32
Case Else
Throw ExceptionUtilities.UnexpectedValue(operatorKind)
End Select
rightType = GetSpecialType(defaultRightSpecialType, right.Syntax, diagnostics)
right = ApplyImplicitConversion(right.Syntax,
rightType,
right, diagnostics)
Else
rightType = right.Type
If rightType Is Nothing Then
Return
End If
End If
Debug.Assert(rightType IsNot Nothing)
Dim defaultLeftSpecialType As SpecialType = SpecialType.None
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
If rightType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse
rightType.IsCharSZArray() OrElse
rightType.IsDBNullType() Then
' For & and Like, a Nothing operand is typed String unless the other operand
' is non-intrinsic (VSW#240203).
' The same goes for DBNull (VSW#278518)
' The same goes for enum types (VSW#288077)
defaultLeftSpecialType = SpecialType.System_String
End If
Case BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift
' Nothing should default to Integer for Shift operations.
defaultLeftSpecialType = SpecialType.System_Int32
End Select
If defaultLeftSpecialType = SpecialType.None OrElse defaultLeftSpecialType = rightType.SpecialType Then
leftType = rightType
Else
leftType = GetSpecialType(defaultLeftSpecialType, left.Syntax, diagnostics)
End If
left = ApplyImplicitConversion(left.Syntax,
leftType,
left, diagnostics)
ElseIf right.IsNothingLiteral() Then
leftType = left.Type
If leftType Is Nothing Then
Return
End If
rightType = leftType
Select Case operatorKind
Case BinaryOperatorKind.Concatenate,
BinaryOperatorKind.Like
If leftType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse
leftType.IsCharSZArray() OrElse
leftType.IsDBNullType() Then
' For & and Like, a Nothing operand is typed String unless the other operand
' is non-intrinsic (VSW#240203).
' The same goes for DBNull (VSW#278518)
' The same goes for enum types (VSW#288077)
If leftType.SpecialType <> SpecialType.System_String Then
rightType = GetSpecialType(SpecialType.System_String, right.Syntax, diagnostics)
End If
End If
End Select
right = ApplyImplicitConversion(right.Syntax,
rightType,
right, diagnostics)
End If
End Sub
Private Function BindUnaryOperator(node As UnaryExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim operand As BoundExpression = BindValue(node.Operand, diagnostics)
Dim preliminaryOperatorKind As UnaryOperatorKind = OverloadResolution.MapUnaryOperatorKind(node.Kind)
If Not operand.HasErrors AndAlso operand.IsNothingLiteral Then
'§11.12.2 Object Operands
'In a unary operator expression, or if both operands are Nothing in a
'binary operator expression, the type of the operation is Integer
Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.Operand, diagnostics)
operand = ApplyImplicitConversion(node.Operand, int32Type, operand, diagnostics)
Else
operand = MakeRValue(operand, diagnostics)
End If
If operand.HasErrors Then
' Suppress any additional diagnostics by overriding DiagnosticBag.
diagnostics = BindingDiagnosticBag.Discarded
End If
Dim intrinsicOperatorType As SpecialType = SpecialType.None
Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
Dim operatorKind As UnaryOperatorKind = OverloadResolution.ResolveUnaryOperator(preliminaryOperatorKind, operand, Me, intrinsicOperatorType, userDefinedOperator, useSiteInfo)
If diagnostics.Add(node, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
If operatorKind = UnaryOperatorKind.UserDefined Then
Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue,
userDefinedOperator.BestResult.Value.Candidate,
Nothing)
If bestCandidate Is Nothing OrElse
Not bestCandidate.IsLifted OrElse
(OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso
OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then
Return BindUserDefinedUnaryOperator(node, preliminaryOperatorKind, operand, userDefinedOperator, diagnostics)
End If
operatorKind = UnaryOperatorKind.Error
End If
If operatorKind = UnaryOperatorKind.Error Then
ReportUndefinedOperatorError(node, operand, diagnostics)
Return New BoundUnaryOperator(node, preliminaryOperatorKind Or UnaryOperatorKind.Error, operand, CheckOverflow, ErrorTypeSymbol.UnknownResultType, HasErrors:=True)
End If
' We are dealing with intrinsic operator
Dim operandType As TypeSymbol = operand.Type
Dim resultType As TypeSymbol = Nothing
If intrinsicOperatorType = SpecialType.None Then
Debug.Assert(operandType.GetNullableUnderlyingTypeOrSelf().IsEnumType())
resultType = operandType
Else
If operandType.GetNullableUnderlyingTypeOrSelf().SpecialType = intrinsicOperatorType Then
resultType = operandType
Else
resultType = GetSpecialType(intrinsicOperatorType, node.Operand, diagnostics)
If operandType.IsNullableType() Then
resultType = DirectCast(operandType.OriginalDefinition, NamedTypeSymbol).Construct(resultType)
End If
End If
End If
Debug.Assert(((operatorKind And UnaryOperatorKind.Lifted) <> 0) = resultType.IsNullableType())
' Option Strict disallows all unary operations on Object operands. Otherwise just warn.
If operandType.SpecialType = SpecialType.System_Object Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.ERR_StrictDisallowsObjectOperand1, node.OperatorToken))
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectMath2, node.OperatorToken))
End If
End If
operand = ApplyImplicitConversion(node.Operand, resultType, operand, diagnostics)
Dim constantValue As ConstantValue = Nothing
If Not operand.HasErrors Then
Dim integerOverflow As Boolean = False
constantValue = OverloadResolution.TryFoldConstantUnaryOperator(operatorKind, operand, resultType, integerOverflow)
' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior.
If constantValue IsNot Nothing AndAlso (constantValue.IsBad OrElse integerOverflow) Then
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, resultType))
' there should be no constant value in case of overflows.
If Not constantValue.IsBad Then
constantValue = constantValue.Bad
End If
End If
End If
Return New BoundUnaryOperator(node, operatorKind, operand, CheckOverflow, constantValue, resultType)
End Function
Private Function BindUserDefinedUnaryOperator(
node As SyntaxNode,
opKind As UnaryOperatorKind,
operand As BoundExpression,
<[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult,
diagnostics As BindingDiagnosticBag
) As BoundUserDefinedUnaryOperator
Debug.Assert(userDefinedOperator.Candidates.Length > 0)
Dim result As BoundExpression
opKind = opKind Or UnaryOperatorKind.UserDefined
If userDefinedOperator.BestResult.HasValue Then
Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value
result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None,
New BoundMethodGroup(node, Nothing,
ImmutableArray.Create(Of MethodSymbol)(
DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)),
LookupResultKind.Good, Nothing,
QualificationKind.Unqualified).MakeCompilerGenerated(),
ImmutableArray.Create(Of BoundExpression)(operand),
bestCandidate,
userDefinedOperator.AsyncLambdaSubToFunctionMismatch,
diagnostics)
If bestCandidate.Candidate.IsLifted Then
opKind = opKind Or UnaryOperatorKind.Lifted
End If
Else
result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good,
ImmutableArray.Create(Of BoundExpression)(operand),
Nothing, userDefinedOperator, diagnostics,
callerInfoOpt:=Nothing)
End If
Return New BoundUserDefinedUnaryOperator(node, opKind, result, result.Type)
End Function
Private Shared Sub ReportUndefinedOperatorError(
syntax As UnaryExpressionSyntax,
operand As BoundExpression,
diagnostics As BindingDiagnosticBag
)
If operand.Type.IsErrorType() Then
Return ' Let's not report more errors.
End If
ReportDiagnostic(diagnostics, syntax, ErrorFactory.ErrorInfo(ERRID.ERR_UnaryOperand2, syntax.OperatorToken, operand.Type))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/VisualBasic/Test/Emit/AssemblyAttributes.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Xunit
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Xunit
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Features/CSharp/Portable/CodeFixes/ConditionalExpressionInStringInterpolation/CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConditionalExpressionInStringInterpolation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddParenthesesAroundConditionalExpressionInInterpolatedString), Shared]
internal class CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider : CodeFixProvider
{
private const string CS8361 = nameof(CS8361); //A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation.Parenthesize the conditional expression.
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider()
{
}
// CS8361 is a syntax error and it is unlikely that there is more than one CS8361 at a time.
public override FixAllProvider? GetFixAllProvider() => null;
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS8361);
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var token = root.FindToken(diagnosticSpan.Start);
var conditionalExpression = token.GetAncestor<ConditionalExpressionSyntax>();
if (conditionalExpression != null)
{
var documentChangeAction = new MyCodeAction(
c => GetChangedDocumentAsync(context.Document, conditionalExpression.SpanStart, c));
context.RegisterCodeFix(documentChangeAction, diagnostic);
}
}
private static async Task<Document> GetChangedDocumentAsync(Document document, int conditionalExpressionSyntaxStartPosition, CancellationToken cancellationToken)
{
// The usual SyntaxTree transformations are complicated if string literals are present in the false part as in
// $"{ condition ? "Success": "Failure" }"
// The colon starts a FormatClause and the double quote left to 'F' therefore ends the interpolated string.
// The text starting with 'F' is parsed as code and the resulting syntax tree is impractical.
// The same problem arises if a } is present in the false part.
// To circumvent these problems this solution
// 1. Inserts an opening parenthesis
// 2. Re-parses the resulting document (now the colon isn't treated as starting a FormatClause anymore)
// 3. Replaces the missing CloseParenToken with a new one
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var openParenthesisPosition = conditionalExpressionSyntaxStartPosition;
var textWithOpenParenthesis = text.Replace(openParenthesisPosition, 0, "(");
var documentWithOpenParenthesis = document.WithText(textWithOpenParenthesis);
var syntaxRoot = await documentWithOpenParenthesis.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var nodeAtInsertPosition = syntaxRoot.FindNode(new TextSpan(openParenthesisPosition, 0));
if (nodeAtInsertPosition is not ParenthesizedExpressionSyntax parenthesizedExpression ||
!parenthesizedExpression.CloseParenToken.IsMissing)
{
return documentWithOpenParenthesis;
}
return await InsertCloseParenthesisAsync(
documentWithOpenParenthesis, parenthesizedExpression, cancellationToken).ConfigureAwait(false);
}
private static async Task<Document> InsertCloseParenthesisAsync(
Document document,
ParenthesizedExpressionSyntax parenthesizedExpression,
CancellationToken cancellationToken)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (parenthesizedExpression.Expression is ConditionalExpressionSyntax conditional &&
parenthesizedExpression.GetAncestor<InterpolatedStringExpressionSyntax>()?.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken)
{
// If they have something like:
//
// var s3 = $""Text1 { true ? ""Text2""[|:|]
// NextLineOfCode();
//
// We will update this initially to:
//
// var s3 = $""Text1 { (true ? ""Text2""[|:|]
// NextLineOfCode();
//
// And we have to decide where the close paren should go. Based on the parse tree, the
// 'NextLineOfCode()' expression will be pulled into the WhenFalse portion of the conditional.
// So placing the close paren after the conditional woudl result in: 'NextLineOfCode())'.
//
// However, the user intent is likely that NextLineOfCode is not part of the conditional
// So instead find the colon and place the close paren after that, producing:
//
// var s3 = $""Text1 { (true ? ""Text2"":)
// NextLineOfCode();
var endToken = sourceText.AreOnSameLine(conditional.ColonToken, conditional.WhenFalse.GetFirstToken())
? conditional.WhenFalse.GetLastToken()
: conditional.ColonToken;
var closeParenPosition = endToken.Span.End;
var textWithCloseParenthesis = sourceText.Replace(closeParenPosition, 0, ")");
return document.WithText(textWithCloseParenthesis);
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newCloseParen = SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(parenthesizedExpression.CloseParenToken);
var parenthesizedExpressionWithClosingParen = parenthesizedExpression.WithCloseParenToken(newCloseParen);
var newRoot = root.ReplaceNode(parenthesizedExpression, parenthesizedExpressionWithClosingParen);
return document.WithSyntaxRoot(newRoot);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpFeaturesResources.Add_parentheses_around_conditional_expression_in_interpolated_string,
createChangedDocument,
CSharpFeaturesResources.Add_parentheses_around_conditional_expression_in_interpolated_string)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConditionalExpressionInStringInterpolation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddParenthesesAroundConditionalExpressionInInterpolatedString), Shared]
internal class CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider : CodeFixProvider
{
private const string CS8361 = nameof(CS8361); //A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation.Parenthesize the conditional expression.
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpAddParenthesesAroundConditionalExpressionInInterpolatedStringCodeFixProvider()
{
}
// CS8361 is a syntax error and it is unlikely that there is more than one CS8361 at a time.
public override FixAllProvider? GetFixAllProvider() => null;
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS8361);
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var token = root.FindToken(diagnosticSpan.Start);
var conditionalExpression = token.GetAncestor<ConditionalExpressionSyntax>();
if (conditionalExpression != null)
{
var documentChangeAction = new MyCodeAction(
c => GetChangedDocumentAsync(context.Document, conditionalExpression.SpanStart, c));
context.RegisterCodeFix(documentChangeAction, diagnostic);
}
}
private static async Task<Document> GetChangedDocumentAsync(Document document, int conditionalExpressionSyntaxStartPosition, CancellationToken cancellationToken)
{
// The usual SyntaxTree transformations are complicated if string literals are present in the false part as in
// $"{ condition ? "Success": "Failure" }"
// The colon starts a FormatClause and the double quote left to 'F' therefore ends the interpolated string.
// The text starting with 'F' is parsed as code and the resulting syntax tree is impractical.
// The same problem arises if a } is present in the false part.
// To circumvent these problems this solution
// 1. Inserts an opening parenthesis
// 2. Re-parses the resulting document (now the colon isn't treated as starting a FormatClause anymore)
// 3. Replaces the missing CloseParenToken with a new one
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var openParenthesisPosition = conditionalExpressionSyntaxStartPosition;
var textWithOpenParenthesis = text.Replace(openParenthesisPosition, 0, "(");
var documentWithOpenParenthesis = document.WithText(textWithOpenParenthesis);
var syntaxRoot = await documentWithOpenParenthesis.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var nodeAtInsertPosition = syntaxRoot.FindNode(new TextSpan(openParenthesisPosition, 0));
if (nodeAtInsertPosition is not ParenthesizedExpressionSyntax parenthesizedExpression ||
!parenthesizedExpression.CloseParenToken.IsMissing)
{
return documentWithOpenParenthesis;
}
return await InsertCloseParenthesisAsync(
documentWithOpenParenthesis, parenthesizedExpression, cancellationToken).ConfigureAwait(false);
}
private static async Task<Document> InsertCloseParenthesisAsync(
Document document,
ParenthesizedExpressionSyntax parenthesizedExpression,
CancellationToken cancellationToken)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (parenthesizedExpression.Expression is ConditionalExpressionSyntax conditional &&
parenthesizedExpression.GetAncestor<InterpolatedStringExpressionSyntax>()?.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken)
{
// If they have something like:
//
// var s3 = $""Text1 { true ? ""Text2""[|:|]
// NextLineOfCode();
//
// We will update this initially to:
//
// var s3 = $""Text1 { (true ? ""Text2""[|:|]
// NextLineOfCode();
//
// And we have to decide where the close paren should go. Based on the parse tree, the
// 'NextLineOfCode()' expression will be pulled into the WhenFalse portion of the conditional.
// So placing the close paren after the conditional woudl result in: 'NextLineOfCode())'.
//
// However, the user intent is likely that NextLineOfCode is not part of the conditional
// So instead find the colon and place the close paren after that, producing:
//
// var s3 = $""Text1 { (true ? ""Text2"":)
// NextLineOfCode();
var endToken = sourceText.AreOnSameLine(conditional.ColonToken, conditional.WhenFalse.GetFirstToken())
? conditional.WhenFalse.GetLastToken()
: conditional.ColonToken;
var closeParenPosition = endToken.Span.End;
var textWithCloseParenthesis = sourceText.Replace(closeParenPosition, 0, ")");
return document.WithText(textWithCloseParenthesis);
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newCloseParen = SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(parenthesizedExpression.CloseParenToken);
var parenthesizedExpressionWithClosingParen = parenthesizedExpression.WithCloseParenToken(newCloseParen);
var newRoot = root.ReplaceNode(parenthesizedExpression, parenthesizedExpressionWithClosingParen);
return document.WithSyntaxRoot(newRoot);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpFeaturesResources.Add_parentheses_around_conditional_expression_in_interpolated_string,
createChangedDocument,
CSharpFeaturesResources.Add_parentheses_around_conditional_expression_in_interpolated_string)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIdeFeatures.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest
{
public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override Task DisposeAsync()
{
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.Reset();
return base.DisposeAsync();
}
[WpfFact]
public void VerifyDefaultUsingStatements()
{
VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("42");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCodeActionsNotAvailableInPreviousSubmission()
{
VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);");
VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing();
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyQuickInfoOnStringDocCommentsFromMetadata()
{
VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }");
VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2);
VisualStudio.InteractiveWindow.InvokeQuickInfo();
var s = VisualStudio.InteractiveWindow.GetQuickInfo();
Assert.Equal("class System.String", s);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void International()
{
VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية();
العربية func = () => System.Console.WriteLine(2);");
VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1);
VisualStudio.InteractiveWindow.InvokeQuickInfo();
var s = VisualStudio.InteractiveWindow.GetQuickInfo();
Assert.Equal("(field) العربية func", s);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;");
VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway()
{
VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;");
VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2);
VisualStudio.InteractiveWindow.PlaceCaret("22");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();");
VisualStudio.InteractiveWindow.SubmitText("something.ToString();");
VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();");
VisualStudio.InteractiveWindow.InsertCode("something.ToString();");
VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.SubmitText("Goo b;");
VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.InsertCode("Goo b;");
VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2);
}
[WpfFact]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();");
VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
}
[WpfFact]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable()
{
VisualStudio.InteractiveWindow.SubmitText("string abc = null;");
VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;");
VisualStudio.InteractiveWindow.InsertCode("int abc = 42;");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void DisabledCommandsPart1()
{
VisualStudio.InteractiveWindow.InsertCode(@"public class Class
{
int field;
public void Method(int x)
{
int abc = 1 + 1;
}
}");
VisualStudio.InteractiveWindow.PlaceCaret("abc");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename));
VisualStudio.InteractiveWindow.PlaceCaret("1 + 1");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod));
VisualStudio.InteractiveWindow.PlaceCaret("Class");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface));
VisualStudio.InteractiveWindow.PlaceCaret("field");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField));
VisualStudio.InteractiveWindow.PlaceCaret("Method");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters));
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters));
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void AddUsing()
{
VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)");
VisualStudio.InteractiveWindow.PlaceCaret("ArrayList");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.InvokeCodeActionList();
VisualStudio.InteractiveWindow.Verify.CodeActions(
new string[] { "using System.Collections;", "System.Collections.ArrayList" },
"using System.Collections;");
VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections;
typeof(ArrayList)");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void QualifyName()
{
VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.PlaceCaret("ArrayList");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.Verify.CodeActions(
new string[] { "using System.Collections;", "System.Collections.ArrayList" },
"System.Collections.ArrayList");
VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest
{
public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override Task DisposeAsync()
{
VisualStudio.Editor.SetUseSuggestionMode(false);
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.Reset();
return base.DisposeAsync();
}
[WpfFact]
public void VerifyDefaultUsingStatements()
{
VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("42");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyCodeActionsNotAvailableInPreviousSubmission()
{
VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);");
VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing();
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void VerifyQuickInfoOnStringDocCommentsFromMetadata()
{
VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }");
VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2);
VisualStudio.InteractiveWindow.InvokeQuickInfo();
var s = VisualStudio.InteractiveWindow.GetQuickInfo();
Assert.Equal("class System.String", s);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void International()
{
VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية();
العربية func = () => System.Console.WriteLine(2);");
VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1);
VisualStudio.InteractiveWindow.InvokeQuickInfo();
var s = VisualStudio.InteractiveWindow.GetQuickInfo();
Assert.Equal("(field) العربية func", s);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;");
VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway()
{
VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;");
VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2);
VisualStudio.InteractiveWindow.PlaceCaret("22");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();");
VisualStudio.InteractiveWindow.SubmitText("something.ToString();");
VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();");
VisualStudio.InteractiveWindow.InsertCode("something.ToString();");
VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.SubmitText("Goo b;");
VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.InsertCode("Goo b;");
VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2);
}
[WpfFact]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText()
{
VisualStudio.InteractiveWindow.SubmitText("class Goo { }");
VisualStudio.InteractiveWindow.SubmitText("Goo a;");
VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();");
VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
}
[WpfFact]
public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable()
{
VisualStudio.InteractiveWindow.SubmitText("string abc = null;");
VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;");
VisualStudio.InteractiveWindow.InsertCode("int abc = 42;");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1);
VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void DisabledCommandsPart1()
{
VisualStudio.InteractiveWindow.InsertCode(@"public class Class
{
int field;
public void Method(int x)
{
int abc = 1 + 1;
}
}");
VisualStudio.InteractiveWindow.PlaceCaret("abc");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename));
VisualStudio.InteractiveWindow.PlaceCaret("1 + 1");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod));
VisualStudio.InteractiveWindow.PlaceCaret("Class");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface));
VisualStudio.InteractiveWindow.PlaceCaret("field");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField));
VisualStudio.InteractiveWindow.PlaceCaret("Method");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters));
Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters));
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void AddUsing()
{
VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)");
VisualStudio.InteractiveWindow.PlaceCaret("ArrayList");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.InvokeCodeActionList();
VisualStudio.InteractiveWindow.Verify.CodeActions(
new string[] { "using System.Collections;", "System.Collections.ArrayList" },
"using System.Collections;");
VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections;
typeof(ArrayList)");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")]
public void QualifyName()
{
VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.PlaceCaret("ArrayList");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace);
VisualStudio.InteractiveWindow.Verify.CodeActions(
new string[] { "using System.Collections;", "System.Collections.ArrayList" },
"System.Collections.ArrayList");
VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)");
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Test/Resources/Core/SymbolsTests/UseSiteErrors/ILErrors.il | // Depends on Unavailable.dll
// ilasm /DLL ILErrors.il /OUTPUT=ILErrors.dll
.assembly extern Unavailable
{
.ver 0:0:0:0
}
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly ILErrors
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.class public auto ansi beforefieldinit ILErrors.ClassMethods
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance int32 modopt([Unavailable]UnavailableClass) ReturnType1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot virtual
instance int32 modopt([Unavailable]UnavailableClass) [] ReturnType2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot virtual
instance void ParameterType1(int32 modopt([Unavailable]UnavailableClass) u) cil managed
{
ret
}
.method public hidebysig newslot virtual
instance void ParameterType2(int32 modopt([Unavailable]UnavailableClass) [] u) cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class ClassMethods
.class interface public abstract auto ansi ILErrors.InterfaceMethods
{
.method public hidebysig newslot abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) ReturnType1() cil managed
{
}
.method public hidebysig newslot abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] ReturnType2() cil managed
{
}
.method public hidebysig newslot abstract virtual
instance void ParameterType1(int32 modopt([Unavailable]UnavailableClass) u) cil managed
{
}
.method public hidebysig newslot abstract virtual
instance void ParameterType2(int32 modopt([Unavailable]UnavailableClass) [] u) cil managed
{
}
} // end of class InterfaceMethods
.class public auto ansi beforefieldinit ILErrors.ClassProperties
extends [mscorlib]System.Object
{
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) get_GetSet1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot specialname virtual
instance void set_GetSet1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_GetSet2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual
instance void set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) get_Get1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_Get2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual
instance void set_Set1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance void set_Set2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 modopt([Unavailable]UnavailableClass) GetSet1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_GetSet1()
.set instance void ILErrors.ClassProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] GetSet2()
{
.set instance void ILErrors.ClassProperties::set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [])
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.ClassProperties::get_GetSet2()
}
.property instance int32 GetSet3()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_GetSet1()
.set instance void ILErrors.ClassProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) Get1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_Get1()
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Get2()
{
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.ClassProperties::get_Get2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Set1()
{
.set instance void ILErrors.ClassProperties::set_Set1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Set2()
{
.set instance void ILErrors.ClassProperties::set_Set2(int32 modopt([Unavailable]UnavailableClass) [])
}
} // end of class ClassProperties
.class interface public abstract auto ansi ILErrors.InterfaceProperties
{
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) get_GetSet1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_GetSet1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_GetSet2() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) get_Get1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_Get2() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_Set1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_Set2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
}
.property instance int32 modopt([Unavailable]UnavailableClass) GetSet1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.InterfaceProperties::get_GetSet1()
.set instance void ILErrors.InterfaceProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] GetSet2()
{
.set instance void ILErrors.InterfaceProperties::set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [])
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.InterfaceProperties::get_GetSet2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Get1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.InterfaceProperties::get_Get1()
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Get2()
{
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.InterfaceProperties::get_Get2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Set1()
{
.set instance void ILErrors.InterfaceProperties::set_Set1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Set2()
{
.set instance void ILErrors.InterfaceProperties::set_Set2(int32 modopt([Unavailable]UnavailableClass) [])
}
} // end of class InterfaceProperties
.class public auto ansi beforefieldinit ILErrors.ClassEvents
extends [mscorlib]System.Object
{
.method public hidebysig newslot specialname virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ClassEvents::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ClassEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.ClassEvents::Event1
} // end of class ILErrors.ClassEvents
.class public auto ansi beforefieldinit ILErrors.ClassEventsNonVirtual
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ClassEventsNonVirtual::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ClassEventsNonVirtual::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.ClassEventsNonVirtual::Event1
} // end of class ILErrors.ClassEventsNonVirtual
.class interface public abstract auto ansi ILErrors.InterfaceEvents
{
.method public hidebysig newslot specialname abstract virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.InterfaceEvents::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.InterfaceEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.InterfaceEvents::Event1
} // end of class ILErrors.InterfaceEvents
.class public auto ansi beforefieldinit ILErrors.ModReqClassEventsNonVirtual
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance void
add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ModReqClassEventsNonVirtual::add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ModReqClassEventsNonVirtual::remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
}
}
.class interface public abstract auto ansi ILErrors.ModReqInterfaceEvents
{
.method public hidebysig newslot specialname abstract virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.event class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ModReqInterfaceEvents::add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ModReqInterfaceEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
}
} | // Depends on Unavailable.dll
// ilasm /DLL ILErrors.il /OUTPUT=ILErrors.dll
.assembly extern Unavailable
{
.ver 0:0:0:0
}
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly ILErrors
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.class public auto ansi beforefieldinit ILErrors.ClassMethods
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance int32 modopt([Unavailable]UnavailableClass) ReturnType1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot virtual
instance int32 modopt([Unavailable]UnavailableClass) [] ReturnType2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot virtual
instance void ParameterType1(int32 modopt([Unavailable]UnavailableClass) u) cil managed
{
ret
}
.method public hidebysig newslot virtual
instance void ParameterType2(int32 modopt([Unavailable]UnavailableClass) [] u) cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class ClassMethods
.class interface public abstract auto ansi ILErrors.InterfaceMethods
{
.method public hidebysig newslot abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) ReturnType1() cil managed
{
}
.method public hidebysig newslot abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] ReturnType2() cil managed
{
}
.method public hidebysig newslot abstract virtual
instance void ParameterType1(int32 modopt([Unavailable]UnavailableClass) u) cil managed
{
}
.method public hidebysig newslot abstract virtual
instance void ParameterType2(int32 modopt([Unavailable]UnavailableClass) [] u) cil managed
{
}
} // end of class InterfaceMethods
.class public auto ansi beforefieldinit ILErrors.ClassProperties
extends [mscorlib]System.Object
{
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) get_GetSet1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot specialname virtual
instance void set_GetSet1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_GetSet2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual
instance void set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) get_Get1() cil managed
{
ldc.i4.0
ret
}
.method public hidebysig newslot specialname virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_Get2() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual
instance void set_Set1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual
instance void set_Set2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 modopt([Unavailable]UnavailableClass) GetSet1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_GetSet1()
.set instance void ILErrors.ClassProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] GetSet2()
{
.set instance void ILErrors.ClassProperties::set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [])
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.ClassProperties::get_GetSet2()
}
.property instance int32 GetSet3()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_GetSet1()
.set instance void ILErrors.ClassProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) Get1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.ClassProperties::get_Get1()
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Get2()
{
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.ClassProperties::get_Get2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Set1()
{
.set instance void ILErrors.ClassProperties::set_Set1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Set2()
{
.set instance void ILErrors.ClassProperties::set_Set2(int32 modopt([Unavailable]UnavailableClass) [])
}
} // end of class ClassProperties
.class interface public abstract auto ansi ILErrors.InterfaceProperties
{
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) get_GetSet1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_GetSet1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_GetSet2() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) get_Get1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 modopt([Unavailable]UnavailableClass) [] get_Get2() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_Set1(int32 modopt([Unavailable]UnavailableClass) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_Set2(int32 modopt([Unavailable]UnavailableClass) [] 'value') cil managed
{
}
.property instance int32 modopt([Unavailable]UnavailableClass) GetSet1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.InterfaceProperties::get_GetSet1()
.set instance void ILErrors.InterfaceProperties::set_GetSet1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] GetSet2()
{
.set instance void ILErrors.InterfaceProperties::set_GetSet2(int32 modopt([Unavailable]UnavailableClass) [])
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.InterfaceProperties::get_GetSet2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Get1()
{
.get instance int32 modopt([Unavailable]UnavailableClass) ILErrors.InterfaceProperties::get_Get1()
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Get2()
{
.get instance int32 modopt([Unavailable]UnavailableClass) [] ILErrors.InterfaceProperties::get_Get2()
}
.property instance int32 modopt([Unavailable]UnavailableClass) Set1()
{
.set instance void ILErrors.InterfaceProperties::set_Set1(int32 modopt([Unavailable]UnavailableClass))
}
.property instance int32 modopt([Unavailable]UnavailableClass) [] Set2()
{
.set instance void ILErrors.InterfaceProperties::set_Set2(int32 modopt([Unavailable]UnavailableClass) [])
}
} // end of class InterfaceProperties
.class public auto ansi beforefieldinit ILErrors.ClassEvents
extends [mscorlib]System.Object
{
.method public hidebysig newslot specialname virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ClassEvents::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ClassEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.ClassEvents::Event1
} // end of class ILErrors.ClassEvents
.class public auto ansi beforefieldinit ILErrors.ClassEventsNonVirtual
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ClassEventsNonVirtual::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ClassEventsNonVirtual::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.ClassEventsNonVirtual::Event1
} // end of class ILErrors.ClassEventsNonVirtual
.class interface public abstract auto ansi ILErrors.InterfaceEvents
{
.method public hidebysig newslot specialname abstract virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.event class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.InterfaceEvents::add_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.InterfaceEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modopt([Unavailable]UnavailableClass) []>)
} // end of event ILErrors.InterfaceEvents::Event1
} // end of class ILErrors.InterfaceEvents
.class public auto ansi beforefieldinit ILErrors.ModReqClassEventsNonVirtual
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance void
add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ModReqClassEventsNonVirtual::add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ModReqClassEventsNonVirtual::remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
}
}
.class interface public abstract auto ansi ILErrors.ModReqInterfaceEvents
{
.method public hidebysig newslot specialname abstract virtual instance void
add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> 'value') cil managed
{
}
.event class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []> Event1
{
.addon instance void ILErrors.ModReqInterfaceEvents::add_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
.removeon instance void ILErrors.ModReqInterfaceEvents::remove_Event1(class [mscorlib]System.Action`1<int32 modreq([Unavailable]UnavailableClass) []>)
}
} | -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Workspaces/DesktopTest/CommandLineProjectWorkspaceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class CommandLineProjectWorkspaceTests
{
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestAddProject_CommandLineProjectAsync()
{
using var tempRoot = new TempRoot();
var tempDirectory = tempRoot.CreateDirectory();
var tempFile = tempDirectory.CreateFile("CSharpClass.cs");
tempFile.WriteAllText("class CSharpClass { }");
using var ws = new AdhocWorkspace();
var commandLine = @"CSharpClass.cs /out:goo.dll /target:library";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, tempDirectory.Path, ws);
ws.AddProject(info);
var project = ws.CurrentSolution.GetProject(info.Id);
Assert.Equal("TestProject", project.Name);
Assert.Equal("goo", project.AssemblyName);
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);
Assert.Equal(1, project.Documents.Count());
var gooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs");
Assert.Equal(0, gooDoc.Folders.Count);
Assert.Equal(tempFile.Path, gooDoc.FilePath);
var text = (await gooDoc.GetTextAsync()).ToString();
Assert.Equal(tempFile.ReadAllText(), text);
var tree = await gooDoc.GetSyntaxRootAsync();
Assert.False(tree.ContainsDiagnostics);
var compilation = await project.GetCompilationAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestLoadProjectFromCommandLine()
{
var commandLine = @"goo.cs subdir\bar.cs /out:goo.dll /target:library";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var ws = new AdhocWorkspace();
ws.AddProject(info);
var project = ws.CurrentSolution.GetProject(info.Id);
Assert.Equal("TestProject", project.Name);
Assert.Equal("goo", project.AssemblyName);
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);
Assert.Equal(2, project.Documents.Count());
var gooDoc = project.Documents.First(d => d.Name == "goo.cs");
Assert.Equal(0, gooDoc.Folders.Count);
Assert.Equal(@"C:\ProjectDirectory\goo.cs", gooDoc.FilePath);
var barDoc = project.Documents.First(d => d.Name == "bar.cs");
Assert.Equal(1, barDoc.Folders.Count);
Assert.Equal("subdir", barDoc.Folders[0]);
Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class CommandLineProjectWorkspaceTests
{
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestAddProject_CommandLineProjectAsync()
{
using var tempRoot = new TempRoot();
var tempDirectory = tempRoot.CreateDirectory();
var tempFile = tempDirectory.CreateFile("CSharpClass.cs");
tempFile.WriteAllText("class CSharpClass { }");
using var ws = new AdhocWorkspace();
var commandLine = @"CSharpClass.cs /out:goo.dll /target:library";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, tempDirectory.Path, ws);
ws.AddProject(info);
var project = ws.CurrentSolution.GetProject(info.Id);
Assert.Equal("TestProject", project.Name);
Assert.Equal("goo", project.AssemblyName);
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);
Assert.Equal(1, project.Documents.Count());
var gooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs");
Assert.Equal(0, gooDoc.Folders.Count);
Assert.Equal(tempFile.Path, gooDoc.FilePath);
var text = (await gooDoc.GetTextAsync()).ToString();
Assert.Equal(tempFile.ReadAllText(), text);
var tree = await gooDoc.GetSyntaxRootAsync();
Assert.False(tree.ContainsDiagnostics);
var compilation = await project.GetCompilationAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestLoadProjectFromCommandLine()
{
var commandLine = @"goo.cs subdir\bar.cs /out:goo.dll /target:library";
var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
var ws = new AdhocWorkspace();
ws.AddProject(info);
var project = ws.CurrentSolution.GetProject(info.Id);
Assert.Equal("TestProject", project.Name);
Assert.Equal("goo", project.AssemblyName);
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);
Assert.Equal(2, project.Documents.Count());
var gooDoc = project.Documents.First(d => d.Name == "goo.cs");
Assert.Equal(0, gooDoc.Folders.Count);
Assert.Equal(@"C:\ProjectDirectory\goo.cs", gooDoc.FilePath);
var barDoc = project.Documents.First(d => d.Name == "bar.cs");
Assert.Equal(1, barDoc.Folders.Count);
Assert.Equal("subdir", barDoc.Folders[0]);
Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath);
}
}
}
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion>
<AssemblyVersion/>
<!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. -->
<NoWarn>$(NoWarn);CA1819</NoWarn>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId>
<PackageDescription>
The build task and targets used by MSBuild to run the C# and VB compilers.
Supports using VBCSCompiler on Windows.
</PackageDescription>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
</PropertyGroup>
<ItemGroup>
<Content Include="*.targets">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Pack>true</Pack>
<BuildAction>None</BuildAction>
<PackageCopyToOutput>true</PackageCopyToOutput>
<PackagePath>contentFiles\any\any</PackagePath>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Shared\NamedPipeUtil.cs" />
<Compile Include="..\..\Shared\BuildServerConnection.cs" />
<Compile Include="..\..\Shared\RuntimeHostInfo.cs" />
<Compile Include="..\Portable\CommitHashAttribute.cs" />
<Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" />
<Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" />
<Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" />
<Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" />
<Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\RoslynString.cs" />
<Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="ErrorString.resx" GenerateSource="true" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" />
<PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" />
</ItemGroup>
<Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" />
</Project>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion>
<AssemblyVersion/>
<!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. -->
<NoWarn>$(NoWarn);CA1819</NoWarn>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId>
<PackageDescription>
The build task and targets used by MSBuild to run the C# and VB compilers.
Supports using VBCSCompiler on Windows.
</PackageDescription>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
</PropertyGroup>
<ItemGroup>
<Content Include="*.targets">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Pack>true</Pack>
<BuildAction>None</BuildAction>
<PackageCopyToOutput>true</PackageCopyToOutput>
<PackagePath>contentFiles\any\any</PackagePath>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Shared\NamedPipeUtil.cs" />
<Compile Include="..\..\Shared\BuildServerConnection.cs" />
<Compile Include="..\..\Shared\RuntimeHostInfo.cs" />
<Compile Include="..\Portable\CommitHashAttribute.cs" />
<Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" />
<Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" />
<Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" />
<Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" />
<Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" />
<Compile Include="..\Portable\InternalUtilities\RoslynString.cs" />
<Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="ErrorString.resx" GenerateSource="true" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" />
<PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" />
</ItemGroup>
<Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" />
</Project>
| -1 |
dotnet/roslyn | 55,450 | Change VB Code Generators to use entire block when reusing method syntax | Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | Soreloser2 | 2021-08-05T23:54:25Z | 2021-08-09T17:01:03Z | 4be8bf68a615ebd030582ce64714823e0a16c640 | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | Change VB Code Generators to use entire block when reusing method syntax. Code Generators have an option to reuse syntax when generating code for a symbol, in which it will copy the declaring syntax reference and use the corresponding node to generate the symbol in the new location. This is used for efficient code movement, such as in Pull Member(s) Up and Extract Class, because you don't need to regenerate lines of code that are written somewhere else.
Currently, when you call `DeclaringSyntaxReferences` on a VB method-like symbol (Function, Sub, Property, Custom Event), you will get back the method statement syntax. This contains the first line of the method block, which is often what is desired for a declaration. However, when we want to reuse syntax, the method statement syntax that `DeclaringSyntaxReferences` gives us only contains the single method line, when we really want to use the entire method block, with all its inner statements and its closing statement. So, we can call the `GetBlockFromBegin` on the method statement, which will give us the entire method block.
This change will bring the reuse syntax option behavior for VB in line with C#, as C#'s `DeclaringSyntaxReferences` return value (or one of them, when declared in multiple locations) actually points to a syntax node that contains the entire body, so no modification is necessary.
A few tests are added to mark this behavior in VB, and are copied for C# (even though behavior hasn't changed). | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/FieldSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class FieldSymbol : Symbol, IFieldSymbol
{
private readonly Symbols.FieldSymbol _underlying;
private ITypeSymbol _lazyType;
public FieldSymbol(Symbols.FieldSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ISymbol IFieldSymbol.AssociatedSymbol
{
get
{
return _underlying.AssociatedSymbol.GetPublicSymbol();
}
}
ITypeSymbol IFieldSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IFieldSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
ImmutableArray<CustomModifier> IFieldSymbol.CustomModifiers
{
get { return _underlying.TypeWithAnnotations.CustomModifiers; }
}
IFieldSymbol IFieldSymbol.OriginalDefinition
{
get
{
return _underlying.OriginalDefinition.GetPublicSymbol();
}
}
IFieldSymbol IFieldSymbol.CorrespondingTupleField
{
get
{
return _underlying.CorrespondingTupleField.GetPublicSymbol();
}
}
bool IFieldSymbol.IsExplicitlyNamedTupleElement
{
get
{
return _underlying.IsExplicitlyNamedTupleElement;
}
}
bool IFieldSymbol.IsConst => _underlying.IsConst;
bool IFieldSymbol.IsReadOnly => _underlying.IsReadOnly;
bool IFieldSymbol.IsVolatile => _underlying.IsVolatile;
bool IFieldSymbol.IsFixedSizeBuffer => _underlying.IsFixedSizeBuffer;
int IFieldSymbol.FixedSize => _underlying.FixedSize;
bool IFieldSymbol.HasConstantValue => _underlying.HasConstantValue;
object IFieldSymbol.ConstantValue => _underlying.ConstantValue;
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitField(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitField(this);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class FieldSymbol : Symbol, IFieldSymbol
{
private readonly Symbols.FieldSymbol _underlying;
private ITypeSymbol _lazyType;
public FieldSymbol(Symbols.FieldSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ISymbol IFieldSymbol.AssociatedSymbol
{
get
{
return _underlying.AssociatedSymbol.GetPublicSymbol();
}
}
ITypeSymbol IFieldSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IFieldSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
ImmutableArray<CustomModifier> IFieldSymbol.CustomModifiers
{
get { return _underlying.TypeWithAnnotations.CustomModifiers; }
}
IFieldSymbol IFieldSymbol.OriginalDefinition
{
get
{
return _underlying.OriginalDefinition.GetPublicSymbol();
}
}
IFieldSymbol IFieldSymbol.CorrespondingTupleField
{
get
{
return _underlying.CorrespondingTupleField.GetPublicSymbol();
}
}
bool IFieldSymbol.IsExplicitlyNamedTupleElement
{
get
{
return _underlying.IsExplicitlyNamedTupleElement;
}
}
bool IFieldSymbol.IsConst => _underlying.IsConst;
bool IFieldSymbol.IsReadOnly => _underlying.IsReadOnly;
bool IFieldSymbol.IsVolatile => _underlying.IsVolatile;
bool IFieldSymbol.IsFixedSizeBuffer => _underlying.IsFixedSizeBuffer;
int IFieldSymbol.FixedSize => _underlying.FixedSize;
bool IFieldSymbol.HasConstantValue => _underlying.HasConstantValue;
object IFieldSymbol.ConstantValue => _underlying.ConstantValue;
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitField(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitField(this);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// A subtype of <see cref="CompletionService"/> that aggregates completions from one or more <see cref="CompletionProvider"/>s.
/// </summary>
public abstract partial class CompletionServiceWithProviders : CompletionService, IEqualityComparer<ImmutableHashSet<string>>
{
private readonly object _gate = new();
private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableArray<CompletionProvider>>> _projectCompletionProvidersMap
= new();
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCompletionProvider> _analyzerReferenceToCompletionProvidersMap
= new();
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCompletionProvider>.CreateValueCallback _createProjectCompletionProvidersProvider
= new(r => new ProjectCompletionProvider(r));
private readonly Dictionary<string, CompletionProvider> _nameToProvider = new();
private readonly Dictionary<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>> _rolesToProviders;
private readonly Func<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>> _createRoleProviders;
private readonly Func<string, CompletionProvider> _getProviderByName;
private readonly Workspace _workspace;
private IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> _importedProviders;
protected CompletionServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_rolesToProviders = new Dictionary<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>>(this);
_createRoleProviders = CreateRoleProviders;
_getProviderByName = GetProviderByName;
}
public override CompletionRules GetRules()
=> CompletionRules.Default;
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
[Obsolete("Built-in providers will be ignored in a future release, please make them MEF exports instead.")]
protected virtual ImmutableArray<CompletionProvider> GetBuiltInProviders()
=> ImmutableArray<CompletionProvider>.Empty;
private IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> GetImportedProviders()
{
if (_importedProviders == null)
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = ExtensionOrderer.Order(
mefExporter.GetExports<CompletionProvider, CompletionProviderMetadata>()
.Where(lz => lz.Metadata.Language == language)
).ToList();
Interlocked.CompareExchange(ref _importedProviders, providers, null);
}
return _importedProviders;
}
private ImmutableArray<CompletionProvider> CreateRoleProviders(ImmutableHashSet<string> roles)
{
var providers = GetAllProviders(roles);
foreach (var provider in providers)
{
_nameToProvider[provider.Name] = provider;
}
return providers;
}
private ImmutableArray<CompletionProvider> GetAllProviders(ImmutableHashSet<string> roles)
{
var imported = GetImportedProviders()
.Where(lz => lz.Metadata.Roles == null || lz.Metadata.Roles.Length == 0 || roles.Overlaps(lz.Metadata.Roles))
.Select(lz => lz.Value);
#pragma warning disable 0618
// We need to keep supporting built-in providers for a while longer since this is a public API.
// https://github.com/dotnet/roslyn/issues/42367
var builtin = GetBuiltInProviders();
#pragma warning restore 0618
return imported.Concat(builtin).ToImmutableArray();
}
protected ImmutableArray<CompletionProvider> GetProviders(ImmutableHashSet<string> roles)
{
roles ??= ImmutableHashSet<string>.Empty;
lock (_gate)
{
return _rolesToProviders.GetOrAdd(roles, _createRoleProviders);
}
}
private ConcatImmutableArray<CompletionProvider> GetFilteredProviders(
Project project, ImmutableHashSet<string> roles, CompletionTrigger trigger, OptionSet options)
{
var allCompletionProviders = FilterProviders(GetProviders(roles, trigger), trigger, options);
var projectCompletionProviders = FilterProviders(GetProjectCompletionProviders(project), trigger, options);
return allCompletionProviders.ConcatFast(projectCompletionProviders);
}
protected virtual ImmutableArray<CompletionProvider> GetProviders(
ImmutableHashSet<string> roles, CompletionTrigger trigger)
{
return GetProviders(roles);
}
private ImmutableArray<CompletionProvider> GetProjectCompletionProviders(Project project)
{
if (project is null)
{
return ImmutableArray<CompletionProvider>.Empty;
}
if (project is null || project.Solution.Workspace.Kind == WorkspaceKind.Interactive)
{
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict completions in Interactive
return ImmutableArray<CompletionProvider>.Empty;
}
if (_projectCompletionProvidersMap.TryGetValue(project.AnalyzerReferences, out var completionProviders))
{
return completionProviders.Value;
}
return GetProjectCompletionProvidersSlow(project);
// Local functions
ImmutableArray<CompletionProvider> GetProjectCompletionProvidersSlow(Project project)
{
return _projectCompletionProvidersMap.GetValue(project.AnalyzerReferences, pId => new StrongBox<ImmutableArray<CompletionProvider>>(ComputeProjectCompletionProviders(project))).Value;
}
ImmutableArray<CompletionProvider> ComputeProjectCompletionProviders(Project project)
{
using var _ = ArrayBuilder<CompletionProvider>.GetInstance(out var builder);
foreach (var reference in project.AnalyzerReferences)
{
var projectCompletionProvider = _analyzerReferenceToCompletionProvidersMap.GetValue(reference, _createProjectCompletionProvidersProvider);
foreach (var completionProvider in projectCompletionProvider.GetExtensions(project.Language))
{
builder.Add(completionProvider);
}
}
return builder.ToImmutable();
}
}
private ImmutableArray<CompletionProvider> FilterProviders(
ImmutableArray<CompletionProvider> providers,
CompletionTrigger trigger,
OptionSet options)
{
if (options.GetOption(CompletionServiceOptions.IsExpandedCompletion))
{
providers = providers.WhereAsArray(p => p.IsExpandItemProvider);
}
// If the caller passed along specific options that affect snippets,
// then defer to those. Otherwise if the caller just wants the default
// behavior, then get the snippets behavior from our own rules.
var optionsRule = options.GetOption(CompletionOptions.SnippetsBehavior, Language);
var snippetsRule = optionsRule != SnippetsRule.Default
? optionsRule
: GetRules().SnippetsRule;
if (snippetsRule is SnippetsRule.Default or
SnippetsRule.NeverInclude)
{
return providers.Where(p => !p.IsSnippetProvider).ToImmutableArray();
}
else if (snippetsRule == SnippetsRule.AlwaysInclude)
{
return providers;
}
else if (snippetsRule == SnippetsRule.IncludeAfterTypingIdentifierQuestionTab)
{
if (trigger.Kind == CompletionTriggerKind.Snippets)
{
return providers.Where(p => p.IsSnippetProvider).ToImmutableArray();
}
else
{
return providers.Where(p => !p.IsSnippetProvider).ToImmutableArray();
}
}
return ImmutableArray<CompletionProvider>.Empty;
}
protected internal CompletionProvider GetProvider(CompletionItem item)
{
CompletionProvider provider = null;
if (item.ProviderName != null)
{
lock (_gate)
{
provider = _nameToProvider.GetOrAdd(item.ProviderName, _getProviderByName);
}
}
return provider;
}
private CompletionProvider GetProviderByName(string providerName)
{
var providers = GetAllProviders(roles: ImmutableHashSet<string>.Empty);
return providers.FirstOrDefault(p => p.Name == providerName);
}
public override async Task<CompletionList> GetCompletionsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
var (completionList, _) = await GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false);
return completionList;
}
private protected async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsWithAvailabilityOfExpandedItemsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var defaultItemSpan = GetDefaultCompletionListSpan(text, caretPosition);
options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var providers = GetFilteredProviders(document.Project, roles, trigger, options);
var completionProviderToIndex = GetCompletionProviderToIndex(providers);
var triggeredProviders = ImmutableArray<CompletionProvider>.Empty;
switch (trigger.Kind)
{
case CompletionTriggerKind.Insertion:
case CompletionTriggerKind.Deletion:
if (ShouldTriggerCompletion(document.Project, text, caretPosition, trigger, roles, options))
{
triggeredProviders = providers.Where(p => p.ShouldTriggerCompletion(document.Project.LanguageServices, text, caretPosition, trigger, options)).ToImmutableArrayOrEmpty();
Debug.Assert(ValidatePossibleTriggerCharacterSet(trigger.Kind, triggeredProviders, document, text, caretPosition, options));
if (triggeredProviders.Length == 0)
{
triggeredProviders = providers.ToImmutableArray();
}
}
break;
default:
triggeredProviders = providers.ToImmutableArray();
break;
}
// Phase 1: Completion Providers decide if they are triggered based on textual analysis
// Phase 2: Completion Providers use syntax to confirm they are triggered, or decide they are not actually triggered and should become an augmenting provider
// Phase 3: Triggered Providers are asked for items
// Phase 4: If any items were provided, all augmenting providers are asked for items
// This allows a provider to be textually triggered but later decide to be an augmenting provider based on deeper syntactic analysis.
var additionalAugmentingProviders = new List<CompletionProvider>();
if (trigger.Kind == CompletionTriggerKind.Insertion)
{
foreach (var provider in triggeredProviders)
{
if (!await provider.IsSyntacticTriggerCharacterAsync(document, caretPosition, trigger, options, cancellationToken).ConfigureAwait(false))
{
additionalAugmentingProviders.Add(provider);
}
}
}
triggeredProviders = triggeredProviders.Except(additionalAugmentingProviders).ToImmutableArray();
// Now, ask all the triggered providers, in parallel, to populate a completion context.
// Note: we keep any context with items *or* with a suggested item.
var (triggeredCompletionContexts, expandItemsAvailableFromTriggeredProviders) = await ComputeNonEmptyCompletionContextsAsync(
document, caretPosition, trigger, options,
defaultItemSpan, triggeredProviders,
cancellationToken).ConfigureAwait(false);
// If we didn't even get any back with items, then there's nothing to do.
// i.e. if only got items back that had only suggestion items, then we don't
// want to show any completion.
if (!triggeredCompletionContexts.Any(cc => cc.Items.Count > 0))
{
return (null, expandItemsAvailableFromTriggeredProviders);
}
// All the contexts should be non-empty or have a suggestion item.
Debug.Assert(triggeredCompletionContexts.All(HasAnyItems));
// See if there were completion contexts provided that were exclusive. If so, then
// that's all we'll return.
var exclusiveContexts = triggeredCompletionContexts.Where(t => t.IsExclusive);
if (exclusiveContexts.Any())
{
return (MergeAndPruneCompletionLists(exclusiveContexts, defaultItemSpan, isExclusive: true),
expandItemsAvailableFromTriggeredProviders);
}
// Shouldn't be any exclusive completion contexts at this point.
Debug.Assert(triggeredCompletionContexts.All(cc => !cc.IsExclusive));
// Great! We had some items. Now we want to see if any of the other providers
// would like to augment the completion list. For example, we might trigger
// enum-completion on space. If enum completion results in any items, then
// we'll want to augment the list with all the regular symbol completion items.
var augmentingProviders = providers.Except(triggeredProviders).ToImmutableArray();
var (augmentingCompletionContexts, expandItemsAvailableFromAugmentingProviders) = await ComputeNonEmptyCompletionContextsAsync(
document, caretPosition, trigger, options, defaultItemSpan,
augmentingProviders, cancellationToken).ConfigureAwait(false);
var allContexts = triggeredCompletionContexts.Concat(augmentingCompletionContexts);
Debug.Assert(allContexts.Length > 0);
// Providers are ordered, but we processed them in our own order. Ensure that the
// groups are properly ordered based on the original providers.
allContexts = allContexts.Sort((p1, p2) => completionProviderToIndex[p1.Provider] - completionProviderToIndex[p2.Provider]);
return (MergeAndPruneCompletionLists(allContexts, defaultItemSpan, isExclusive: false),
(expandItemsAvailableFromTriggeredProviders || expandItemsAvailableFromAugmentingProviders));
}
private static bool ValidatePossibleTriggerCharacterSet(CompletionTriggerKind completionTriggerKind, IEnumerable<CompletionProvider> triggeredProviders,
Document document, SourceText text, int caretPosition, OptionSet optionSet)
{
// Only validate on insertion triggers.
if (completionTriggerKind != CompletionTriggerKind.Insertion)
{
return true;
}
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
if (caretPosition > 0 && syntaxFactsService != null)
{
// The trigger character has already been inserted before the current caret position.
var character = text[caretPosition - 1];
// Identifier characters are not part of the possible trigger character set, so don't validate them.
var isIdentifierCharacter = syntaxFactsService.IsIdentifierStartCharacter(character) || syntaxFactsService.IsIdentifierEscapeCharacter(character);
if (isIdentifierCharacter)
{
return true;
}
// Only verify against built in providers. 3rd party ones do not necessarily implement the possible trigger characters API.
foreach (var provider in triggeredProviders)
{
if (provider is LSPCompletionProvider lspProvider && lspProvider.IsInsertionTrigger(text, caretPosition - 1, optionSet))
{
if (!lspProvider.TriggerCharacters.Contains(character))
{
Debug.Assert(lspProvider.TriggerCharacters.Contains(character),
$"the character {character} is not a valid trigger character for {lspProvider.Name}");
}
}
}
}
return true;
}
private static bool HasAnyItems(CompletionContext cc)
=> cc.Items.Count > 0 || cc.SuggestionModeItem != null;
private async Task<(ImmutableArray<CompletionContext>, bool)> ComputeNonEmptyCompletionContextsAsync(
Document document, int caretPosition, CompletionTrigger trigger,
OptionSet options, TextSpan defaultItemSpan,
ImmutableArray<CompletionProvider> providers,
CancellationToken cancellationToken)
{
var completionContextTasks = new List<Task<CompletionContext>>();
foreach (var provider in providers)
{
completionContextTasks.Add(GetContextAsync(
provider, document, caretPosition, trigger,
options, defaultItemSpan, cancellationToken));
}
var completionContexts = await Task.WhenAll(completionContextTasks).ConfigureAwait(false);
var nonEmptyContexts = completionContexts.Where(HasAnyItems).ToImmutableArray();
var shouldShowExpander = completionContexts.Any(context => context.ExpandItemsAvailable);
return (nonEmptyContexts, shouldShowExpander);
}
private CompletionList MergeAndPruneCompletionLists(
IEnumerable<CompletionContext> completionContexts,
TextSpan defaultSpan,
bool isExclusive)
{
// See if any contexts changed the completion list span. If so, the first context that
// changed it 'wins' and picks the span that will be used for all items in the completion
// list. If no contexts changed it, then just use the default span provided by the service.
var finalCompletionListSpan = completionContexts.FirstOrDefault(c => c.CompletionListSpan != defaultSpan)?.CompletionListSpan ?? defaultSpan;
using var displayNameToItemsMap = new DisplayNameToItemsMap(this);
CompletionItem suggestionModeItem = null;
foreach (var context in completionContexts)
{
Debug.Assert(context != null);
foreach (var item in context.Items)
{
Debug.Assert(item != null);
displayNameToItemsMap.Add(item);
}
// first one wins
suggestionModeItem ??= context.SuggestionModeItem;
}
if (displayNameToItemsMap.IsEmpty)
{
return CompletionList.Empty;
}
// TODO(DustinCa): Revisit performance of this.
using var _ = ArrayBuilder<CompletionItem>.GetInstance(displayNameToItemsMap.Count, out var builder);
builder.AddRange(displayNameToItemsMap);
builder.Sort();
return CompletionList.Create(
finalCompletionListSpan,
builder.ToImmutable(),
GetRules(),
suggestionModeItem,
isExclusive);
}
/// <summary>
/// Determines if the items are similar enough they should be represented by a single item in the list.
/// </summary>
protected virtual bool ItemsMatch(CompletionItem item, CompletionItem existingItem)
{
return item.Span == existingItem.Span
&& item.SortText == existingItem.SortText;
}
/// <summary>
/// Determines which of two items should represent the matching pair.
/// </summary>
protected virtual CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem)
{
// the item later in the sort order (determined by provider order) wins?
return item;
}
private static Dictionary<CompletionProvider, int> GetCompletionProviderToIndex(ConcatImmutableArray<CompletionProvider> completionProviders)
{
var result = new Dictionary<CompletionProvider, int>(completionProviders.Length);
var i = 0;
foreach (var completionProvider in completionProviders)
{
result[completionProvider] = i;
i++;
}
return result;
}
private async Task<CompletionContext> GetContextAsync(
CompletionProvider provider,
Document document,
int position,
CompletionTrigger triggerInfo,
OptionSet options,
TextSpan? defaultSpan,
CancellationToken cancellationToken)
{
options ??= document.Project.Solution.Workspace.Options;
if (defaultSpan == null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
defaultSpan = GetDefaultCompletionListSpan(text, position);
}
var context = new CompletionContext(provider, document, position, defaultSpan.Value, triggerInfo, options, cancellationToken);
await provider.ProvideCompletionsAsync(context).ConfigureAwait(false);
return context;
}
public override Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken = default)
{
var provider = GetProvider(item);
return provider != null
? provider.GetDescriptionAsync(document, item, cancellationToken)
: Task.FromResult(CompletionDescription.Empty);
}
public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null)
{
var document = text.GetOpenDocumentInCurrentContextWithChanges();
return ShouldTriggerCompletion(document?.Project, text, caretPosition, trigger, roles, options);
}
internal override bool ShouldTriggerCompletion(
Project project, SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null)
{
options ??= _workspace.Options;
if (!options.GetOption(CompletionOptions.TriggerOnTyping, Language))
{
return false;
}
if (trigger.Kind == CompletionTriggerKind.Deletion && SupportsTriggerOnDeletion(options))
{
return Char.IsLetterOrDigit(trigger.Character) || trigger.Character == '.';
}
var providers = GetFilteredProviders(project, roles, trigger, options);
return providers.Any(p => p.ShouldTriggerCompletion(project?.LanguageServices, text, caretPosition, trigger, options));
}
internal virtual bool SupportsTriggerOnDeletion(OptionSet options)
{
var opt = options.GetOption(CompletionOptions.TriggerOnDeletion, Language);
return opt == true;
}
public override async Task<CompletionChange> GetChangeAsync(
Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken)
{
var provider = GetProvider(item);
if (provider != null)
{
return await provider.GetChangeAsync(document, item, commitKey, cancellationToken).ConfigureAwait(false);
}
else
{
return CompletionChange.Create(new TextChange(item.Span, item.DisplayText));
}
}
bool IEqualityComparer<ImmutableHashSet<string>>.Equals(ImmutableHashSet<string> x, ImmutableHashSet<string> y)
{
if (x == y)
{
return true;
}
if (x.Count != y.Count)
{
return false;
}
foreach (var v in x)
{
if (!y.Contains(v))
{
return false;
}
}
return true;
}
int IEqualityComparer<ImmutableHashSet<string>>.GetHashCode(ImmutableHashSet<string> obj)
{
var hash = 0;
foreach (var o in obj)
{
hash += o.GetHashCode();
}
return hash;
}
private class DisplayNameToItemsMap : IEnumerable<CompletionItem>, IDisposable
{
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize array allocations.
// Set the size of pool to a small number 5 because we don't expect more than a
// couple of callers at the same time.
private static readonly ObjectPool<Dictionary<string, object>> s_uniqueSourcesPool
= new(factory: () => new(), size: 5);
private readonly Dictionary<string, object> _displayNameToItemsMap;
private readonly CompletionServiceWithProviders _service;
public int Count { get; private set; }
public DisplayNameToItemsMap(CompletionServiceWithProviders service)
{
_service = service;
_displayNameToItemsMap = s_uniqueSourcesPool.Allocate();
}
public void Dispose()
{
_displayNameToItemsMap.Clear();
s_uniqueSourcesPool.Free(_displayNameToItemsMap);
}
public bool IsEmpty => _displayNameToItemsMap.Count == 0;
public void Add(CompletionItem item)
{
var entireDisplayText = item.GetEntireDisplayText();
if (!_displayNameToItemsMap.TryGetValue(entireDisplayText, out var value))
{
Count++;
_displayNameToItemsMap.Add(entireDisplayText, item);
return;
}
// If two items have the same display text choose which one to keep.
// If they don't actually match keep both.
if (value is CompletionItem sameNamedItem)
{
if (_service.ItemsMatch(item, sameNamedItem))
{
_displayNameToItemsMap[entireDisplayText] = _service.GetBetterItem(item, sameNamedItem);
return;
}
Count++;
// Matching items should be rare, no need to use object pool for this.
_displayNameToItemsMap[entireDisplayText] = new List<CompletionItem>() { sameNamedItem, item };
}
else if (value is List<CompletionItem> sameNamedItems)
{
for (var i = 0; i < sameNamedItems.Count; i++)
{
var existingItem = sameNamedItems[i];
if (_service.ItemsMatch(item, existingItem))
{
sameNamedItems[i] = _service.GetBetterItem(item, existingItem);
return;
}
}
Count++;
sameNamedItems.Add(item);
}
}
public IEnumerator<CompletionItem> GetEnumerator()
{
foreach (var value in _displayNameToItemsMap.Values)
{
if (value is CompletionItem sameNamedItem)
{
yield return sameNamedItem;
}
else if (value is List<CompletionItem> sameNamedItems)
{
foreach (var item in sameNamedItems)
{
yield return item;
}
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly CompletionServiceWithProviders _completionServiceWithProviders;
public TestAccessor(CompletionServiceWithProviders completionServiceWithProviders)
=> _completionServiceWithProviders = completionServiceWithProviders;
internal ImmutableArray<CompletionProvider> GetAllProviders(ImmutableHashSet<string> roles)
=> _completionServiceWithProviders.GetAllProviders(roles);
internal Task<CompletionContext> GetContextAsync(
CompletionProvider provider,
Document document,
int position,
CompletionTrigger triggerInfo,
OptionSet options,
CancellationToken cancellationToken)
{
return _completionServiceWithProviders.GetContextAsync(
provider,
document,
position,
triggerInfo,
options,
defaultSpan: null,
cancellationToken);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// A subtype of <see cref="CompletionService"/> that aggregates completions from one or more <see cref="CompletionProvider"/>s.
/// </summary>
public abstract partial class CompletionServiceWithProviders : CompletionService, IEqualityComparer<ImmutableHashSet<string>>
{
private readonly object _gate = new();
private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableArray<CompletionProvider>>> _projectCompletionProvidersMap
= new();
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCompletionProvider> _analyzerReferenceToCompletionProvidersMap
= new();
private readonly ConditionalWeakTable<AnalyzerReference, ProjectCompletionProvider>.CreateValueCallback _createProjectCompletionProvidersProvider
= new(r => new ProjectCompletionProvider(r));
private readonly Dictionary<string, CompletionProvider> _nameToProvider = new();
private readonly Dictionary<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>> _rolesToProviders;
private readonly Func<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>> _createRoleProviders;
private readonly Func<string, CompletionProvider> _getProviderByName;
private readonly Workspace _workspace;
private IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> _importedProviders;
protected CompletionServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_rolesToProviders = new Dictionary<ImmutableHashSet<string>, ImmutableArray<CompletionProvider>>(this);
_createRoleProviders = CreateRoleProviders;
_getProviderByName = GetProviderByName;
}
public override CompletionRules GetRules()
=> CompletionRules.Default;
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
[Obsolete("Built-in providers will be ignored in a future release, please make them MEF exports instead.")]
protected virtual ImmutableArray<CompletionProvider> GetBuiltInProviders()
=> ImmutableArray<CompletionProvider>.Empty;
internal IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> GetImportedProviders()
{
if (_importedProviders == null)
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = ExtensionOrderer.Order(
mefExporter.GetExports<CompletionProvider, CompletionProviderMetadata>()
.Where(lz => lz.Metadata.Language == language)
).ToList();
Interlocked.CompareExchange(ref _importedProviders, providers, null);
}
return _importedProviders;
}
private ImmutableArray<CompletionProvider> CreateRoleProviders(ImmutableHashSet<string> roles)
{
var providers = GetAllProviders(roles);
foreach (var provider in providers)
{
_nameToProvider[provider.Name] = provider;
}
return providers;
}
private ImmutableArray<CompletionProvider> GetAllProviders(ImmutableHashSet<string> roles)
{
var imported = GetImportedProviders()
.Where(lz => lz.Metadata.Roles == null || lz.Metadata.Roles.Length == 0 || roles.Overlaps(lz.Metadata.Roles))
.Select(lz => lz.Value);
#pragma warning disable 0618
// We need to keep supporting built-in providers for a while longer since this is a public API.
// https://github.com/dotnet/roslyn/issues/42367
var builtin = GetBuiltInProviders();
#pragma warning restore 0618
return imported.Concat(builtin).ToImmutableArray();
}
protected ImmutableArray<CompletionProvider> GetProviders(ImmutableHashSet<string> roles)
{
roles ??= ImmutableHashSet<string>.Empty;
lock (_gate)
{
return _rolesToProviders.GetOrAdd(roles, _createRoleProviders);
}
}
private ConcatImmutableArray<CompletionProvider> GetFilteredProviders(
Project project, ImmutableHashSet<string> roles, CompletionTrigger trigger, OptionSet options)
{
var allCompletionProviders = FilterProviders(GetProviders(roles, trigger), trigger, options);
var projectCompletionProviders = FilterProviders(GetProjectCompletionProviders(project), trigger, options);
return allCompletionProviders.ConcatFast(projectCompletionProviders);
}
protected virtual ImmutableArray<CompletionProvider> GetProviders(
ImmutableHashSet<string> roles, CompletionTrigger trigger)
{
return GetProviders(roles);
}
private ImmutableArray<CompletionProvider> GetProjectCompletionProviders(Project project)
{
if (project is null)
{
return ImmutableArray<CompletionProvider>.Empty;
}
if (project is null || project.Solution.Workspace.Kind == WorkspaceKind.Interactive)
{
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict completions in Interactive
return ImmutableArray<CompletionProvider>.Empty;
}
if (_projectCompletionProvidersMap.TryGetValue(project.AnalyzerReferences, out var completionProviders))
{
return completionProviders.Value;
}
return GetProjectCompletionProvidersSlow(project);
// Local functions
ImmutableArray<CompletionProvider> GetProjectCompletionProvidersSlow(Project project)
{
return _projectCompletionProvidersMap.GetValue(project.AnalyzerReferences, pId => new StrongBox<ImmutableArray<CompletionProvider>>(ComputeProjectCompletionProviders(project))).Value;
}
ImmutableArray<CompletionProvider> ComputeProjectCompletionProviders(Project project)
{
using var _ = ArrayBuilder<CompletionProvider>.GetInstance(out var builder);
foreach (var reference in project.AnalyzerReferences)
{
var projectCompletionProvider = _analyzerReferenceToCompletionProvidersMap.GetValue(reference, _createProjectCompletionProvidersProvider);
foreach (var completionProvider in projectCompletionProvider.GetExtensions(project.Language))
{
builder.Add(completionProvider);
}
}
return builder.ToImmutable();
}
}
private ImmutableArray<CompletionProvider> FilterProviders(
ImmutableArray<CompletionProvider> providers,
CompletionTrigger trigger,
OptionSet options)
{
if (options.GetOption(CompletionServiceOptions.IsExpandedCompletion))
{
providers = providers.WhereAsArray(p => p.IsExpandItemProvider);
}
// If the caller passed along specific options that affect snippets,
// then defer to those. Otherwise if the caller just wants the default
// behavior, then get the snippets behavior from our own rules.
var optionsRule = options.GetOption(CompletionOptions.SnippetsBehavior, Language);
var snippetsRule = optionsRule != SnippetsRule.Default
? optionsRule
: GetRules().SnippetsRule;
if (snippetsRule is SnippetsRule.Default or
SnippetsRule.NeverInclude)
{
return providers.Where(p => !p.IsSnippetProvider).ToImmutableArray();
}
else if (snippetsRule == SnippetsRule.AlwaysInclude)
{
return providers;
}
else if (snippetsRule == SnippetsRule.IncludeAfterTypingIdentifierQuestionTab)
{
if (trigger.Kind == CompletionTriggerKind.Snippets)
{
return providers.Where(p => p.IsSnippetProvider).ToImmutableArray();
}
else
{
return providers.Where(p => !p.IsSnippetProvider).ToImmutableArray();
}
}
return ImmutableArray<CompletionProvider>.Empty;
}
protected internal CompletionProvider GetProvider(CompletionItem item)
{
CompletionProvider provider = null;
if (item.ProviderName != null)
{
lock (_gate)
{
provider = _nameToProvider.GetOrAdd(item.ProviderName, _getProviderByName);
}
}
return provider;
}
private CompletionProvider GetProviderByName(string providerName)
{
var providers = GetAllProviders(roles: ImmutableHashSet<string>.Empty);
return providers.FirstOrDefault(p => p.Name == providerName);
}
public override async Task<CompletionList> GetCompletionsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
var (completionList, _) = await GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false);
return completionList;
}
private protected async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsWithAvailabilityOfExpandedItemsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var defaultItemSpan = GetDefaultCompletionListSpan(text, caretPosition);
options ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var providers = GetFilteredProviders(document.Project, roles, trigger, options);
var completionProviderToIndex = GetCompletionProviderToIndex(providers);
var triggeredProviders = ImmutableArray<CompletionProvider>.Empty;
switch (trigger.Kind)
{
case CompletionTriggerKind.Insertion:
case CompletionTriggerKind.Deletion:
if (ShouldTriggerCompletion(document.Project, text, caretPosition, trigger, roles, options))
{
triggeredProviders = providers.Where(p => p.ShouldTriggerCompletion(document.Project.LanguageServices, text, caretPosition, trigger, options)).ToImmutableArrayOrEmpty();
Debug.Assert(ValidatePossibleTriggerCharacterSet(trigger.Kind, triggeredProviders, document, text, caretPosition, options));
if (triggeredProviders.Length == 0)
{
triggeredProviders = providers.ToImmutableArray();
}
}
break;
default:
triggeredProviders = providers.ToImmutableArray();
break;
}
// Phase 1: Completion Providers decide if they are triggered based on textual analysis
// Phase 2: Completion Providers use syntax to confirm they are triggered, or decide they are not actually triggered and should become an augmenting provider
// Phase 3: Triggered Providers are asked for items
// Phase 4: If any items were provided, all augmenting providers are asked for items
// This allows a provider to be textually triggered but later decide to be an augmenting provider based on deeper syntactic analysis.
var additionalAugmentingProviders = new List<CompletionProvider>();
if (trigger.Kind == CompletionTriggerKind.Insertion)
{
foreach (var provider in triggeredProviders)
{
if (!await provider.IsSyntacticTriggerCharacterAsync(document, caretPosition, trigger, options, cancellationToken).ConfigureAwait(false))
{
additionalAugmentingProviders.Add(provider);
}
}
}
triggeredProviders = triggeredProviders.Except(additionalAugmentingProviders).ToImmutableArray();
// Now, ask all the triggered providers, in parallel, to populate a completion context.
// Note: we keep any context with items *or* with a suggested item.
var (triggeredCompletionContexts, expandItemsAvailableFromTriggeredProviders) = await ComputeNonEmptyCompletionContextsAsync(
document, caretPosition, trigger, options,
defaultItemSpan, triggeredProviders,
cancellationToken).ConfigureAwait(false);
// If we didn't even get any back with items, then there's nothing to do.
// i.e. if only got items back that had only suggestion items, then we don't
// want to show any completion.
if (!triggeredCompletionContexts.Any(cc => cc.Items.Count > 0))
{
return (null, expandItemsAvailableFromTriggeredProviders);
}
// All the contexts should be non-empty or have a suggestion item.
Debug.Assert(triggeredCompletionContexts.All(HasAnyItems));
// See if there were completion contexts provided that were exclusive. If so, then
// that's all we'll return.
var exclusiveContexts = triggeredCompletionContexts.Where(t => t.IsExclusive);
if (exclusiveContexts.Any())
{
return (MergeAndPruneCompletionLists(exclusiveContexts, defaultItemSpan, isExclusive: true),
expandItemsAvailableFromTriggeredProviders);
}
// Shouldn't be any exclusive completion contexts at this point.
Debug.Assert(triggeredCompletionContexts.All(cc => !cc.IsExclusive));
// Great! We had some items. Now we want to see if any of the other providers
// would like to augment the completion list. For example, we might trigger
// enum-completion on space. If enum completion results in any items, then
// we'll want to augment the list with all the regular symbol completion items.
var augmentingProviders = providers.Except(triggeredProviders).ToImmutableArray();
var (augmentingCompletionContexts, expandItemsAvailableFromAugmentingProviders) = await ComputeNonEmptyCompletionContextsAsync(
document, caretPosition, trigger, options, defaultItemSpan,
augmentingProviders, cancellationToken).ConfigureAwait(false);
var allContexts = triggeredCompletionContexts.Concat(augmentingCompletionContexts);
Debug.Assert(allContexts.Length > 0);
// Providers are ordered, but we processed them in our own order. Ensure that the
// groups are properly ordered based on the original providers.
allContexts = allContexts.Sort((p1, p2) => completionProviderToIndex[p1.Provider] - completionProviderToIndex[p2.Provider]);
return (MergeAndPruneCompletionLists(allContexts, defaultItemSpan, isExclusive: false),
(expandItemsAvailableFromTriggeredProviders || expandItemsAvailableFromAugmentingProviders));
}
private static bool ValidatePossibleTriggerCharacterSet(CompletionTriggerKind completionTriggerKind, IEnumerable<CompletionProvider> triggeredProviders,
Document document, SourceText text, int caretPosition, OptionSet optionSet)
{
// Only validate on insertion triggers.
if (completionTriggerKind != CompletionTriggerKind.Insertion)
{
return true;
}
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
if (caretPosition > 0 && syntaxFactsService != null)
{
// The trigger character has already been inserted before the current caret position.
var character = text[caretPosition - 1];
// Identifier characters are not part of the possible trigger character set, so don't validate them.
var isIdentifierCharacter = syntaxFactsService.IsIdentifierStartCharacter(character) || syntaxFactsService.IsIdentifierEscapeCharacter(character);
if (isIdentifierCharacter)
{
return true;
}
// Only verify against built in providers. 3rd party ones do not necessarily implement the possible trigger characters API.
foreach (var provider in triggeredProviders)
{
if (provider is LSPCompletionProvider lspProvider && lspProvider.IsInsertionTrigger(text, caretPosition - 1, optionSet))
{
if (!lspProvider.TriggerCharacters.Contains(character))
{
Debug.Assert(lspProvider.TriggerCharacters.Contains(character),
$"the character {character} is not a valid trigger character for {lspProvider.Name}");
}
}
}
}
return true;
}
private static bool HasAnyItems(CompletionContext cc)
=> cc.Items.Count > 0 || cc.SuggestionModeItem != null;
private async Task<(ImmutableArray<CompletionContext>, bool)> ComputeNonEmptyCompletionContextsAsync(
Document document, int caretPosition, CompletionTrigger trigger,
OptionSet options, TextSpan defaultItemSpan,
ImmutableArray<CompletionProvider> providers,
CancellationToken cancellationToken)
{
var completionContextTasks = new List<Task<CompletionContext>>();
foreach (var provider in providers)
{
completionContextTasks.Add(GetContextAsync(
provider, document, caretPosition, trigger,
options, defaultItemSpan, cancellationToken));
}
var completionContexts = await Task.WhenAll(completionContextTasks).ConfigureAwait(false);
var nonEmptyContexts = completionContexts.Where(HasAnyItems).ToImmutableArray();
var shouldShowExpander = completionContexts.Any(context => context.ExpandItemsAvailable);
return (nonEmptyContexts, shouldShowExpander);
}
private CompletionList MergeAndPruneCompletionLists(
IEnumerable<CompletionContext> completionContexts,
TextSpan defaultSpan,
bool isExclusive)
{
// See if any contexts changed the completion list span. If so, the first context that
// changed it 'wins' and picks the span that will be used for all items in the completion
// list. If no contexts changed it, then just use the default span provided by the service.
var finalCompletionListSpan = completionContexts.FirstOrDefault(c => c.CompletionListSpan != defaultSpan)?.CompletionListSpan ?? defaultSpan;
using var displayNameToItemsMap = new DisplayNameToItemsMap(this);
CompletionItem suggestionModeItem = null;
foreach (var context in completionContexts)
{
Debug.Assert(context != null);
foreach (var item in context.Items)
{
Debug.Assert(item != null);
displayNameToItemsMap.Add(item);
}
// first one wins
suggestionModeItem ??= context.SuggestionModeItem;
}
if (displayNameToItemsMap.IsEmpty)
{
return CompletionList.Empty;
}
// TODO(DustinCa): Revisit performance of this.
using var _ = ArrayBuilder<CompletionItem>.GetInstance(displayNameToItemsMap.Count, out var builder);
builder.AddRange(displayNameToItemsMap);
builder.Sort();
return CompletionList.Create(
finalCompletionListSpan,
builder.ToImmutable(),
GetRules(),
suggestionModeItem,
isExclusive);
}
/// <summary>
/// Determines if the items are similar enough they should be represented by a single item in the list.
/// </summary>
protected virtual bool ItemsMatch(CompletionItem item, CompletionItem existingItem)
{
return item.Span == existingItem.Span
&& item.SortText == existingItem.SortText;
}
/// <summary>
/// Determines which of two items should represent the matching pair.
/// </summary>
protected virtual CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem)
{
// the item later in the sort order (determined by provider order) wins?
return item;
}
private static Dictionary<CompletionProvider, int> GetCompletionProviderToIndex(ConcatImmutableArray<CompletionProvider> completionProviders)
{
var result = new Dictionary<CompletionProvider, int>(completionProviders.Length);
var i = 0;
foreach (var completionProvider in completionProviders)
{
result[completionProvider] = i;
i++;
}
return result;
}
private async Task<CompletionContext> GetContextAsync(
CompletionProvider provider,
Document document,
int position,
CompletionTrigger triggerInfo,
OptionSet options,
TextSpan? defaultSpan,
CancellationToken cancellationToken)
{
options ??= document.Project.Solution.Workspace.Options;
if (defaultSpan == null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
defaultSpan = GetDefaultCompletionListSpan(text, position);
}
var context = new CompletionContext(provider, document, position, defaultSpan.Value, triggerInfo, options, cancellationToken);
await provider.ProvideCompletionsAsync(context).ConfigureAwait(false);
return context;
}
public override Task<CompletionDescription> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken = default)
{
var provider = GetProvider(item);
return provider != null
? provider.GetDescriptionAsync(document, item, cancellationToken)
: Task.FromResult(CompletionDescription.Empty);
}
public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null)
{
var document = text.GetOpenDocumentInCurrentContextWithChanges();
return ShouldTriggerCompletion(document?.Project, text, caretPosition, trigger, roles, options);
}
internal override bool ShouldTriggerCompletion(
Project project, SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet<string> roles = null, OptionSet options = null)
{
options ??= _workspace.Options;
if (!options.GetOption(CompletionOptions.TriggerOnTyping, Language))
{
return false;
}
if (trigger.Kind == CompletionTriggerKind.Deletion && SupportsTriggerOnDeletion(options))
{
return Char.IsLetterOrDigit(trigger.Character) || trigger.Character == '.';
}
var providers = GetFilteredProviders(project, roles, trigger, options);
return providers.Any(p => p.ShouldTriggerCompletion(project?.LanguageServices, text, caretPosition, trigger, options));
}
internal virtual bool SupportsTriggerOnDeletion(OptionSet options)
{
var opt = options.GetOption(CompletionOptions.TriggerOnDeletion, Language);
return opt == true;
}
public override async Task<CompletionChange> GetChangeAsync(
Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken)
{
var provider = GetProvider(item);
if (provider != null)
{
return await provider.GetChangeAsync(document, item, commitKey, cancellationToken).ConfigureAwait(false);
}
else
{
return CompletionChange.Create(new TextChange(item.Span, item.DisplayText));
}
}
bool IEqualityComparer<ImmutableHashSet<string>>.Equals(ImmutableHashSet<string> x, ImmutableHashSet<string> y)
{
if (x == y)
{
return true;
}
if (x.Count != y.Count)
{
return false;
}
foreach (var v in x)
{
if (!y.Contains(v))
{
return false;
}
}
return true;
}
int IEqualityComparer<ImmutableHashSet<string>>.GetHashCode(ImmutableHashSet<string> obj)
{
var hash = 0;
foreach (var o in obj)
{
hash += o.GetHashCode();
}
return hash;
}
private class DisplayNameToItemsMap : IEnumerable<CompletionItem>, IDisposable
{
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize array allocations.
// Set the size of pool to a small number 5 because we don't expect more than a
// couple of callers at the same time.
private static readonly ObjectPool<Dictionary<string, object>> s_uniqueSourcesPool
= new(factory: () => new(), size: 5);
private readonly Dictionary<string, object> _displayNameToItemsMap;
private readonly CompletionServiceWithProviders _service;
public int Count { get; private set; }
public DisplayNameToItemsMap(CompletionServiceWithProviders service)
{
_service = service;
_displayNameToItemsMap = s_uniqueSourcesPool.Allocate();
}
public void Dispose()
{
_displayNameToItemsMap.Clear();
s_uniqueSourcesPool.Free(_displayNameToItemsMap);
}
public bool IsEmpty => _displayNameToItemsMap.Count == 0;
public void Add(CompletionItem item)
{
var entireDisplayText = item.GetEntireDisplayText();
if (!_displayNameToItemsMap.TryGetValue(entireDisplayText, out var value))
{
Count++;
_displayNameToItemsMap.Add(entireDisplayText, item);
return;
}
// If two items have the same display text choose which one to keep.
// If they don't actually match keep both.
if (value is CompletionItem sameNamedItem)
{
if (_service.ItemsMatch(item, sameNamedItem))
{
_displayNameToItemsMap[entireDisplayText] = _service.GetBetterItem(item, sameNamedItem);
return;
}
Count++;
// Matching items should be rare, no need to use object pool for this.
_displayNameToItemsMap[entireDisplayText] = new List<CompletionItem>() { sameNamedItem, item };
}
else if (value is List<CompletionItem> sameNamedItems)
{
for (var i = 0; i < sameNamedItems.Count; i++)
{
var existingItem = sameNamedItems[i];
if (_service.ItemsMatch(item, existingItem))
{
sameNamedItems[i] = _service.GetBetterItem(item, existingItem);
return;
}
}
Count++;
sameNamedItems.Add(item);
}
}
public IEnumerator<CompletionItem> GetEnumerator()
{
foreach (var value in _displayNameToItemsMap.Values)
{
if (value is CompletionItem sameNamedItem)
{
yield return sameNamedItem;
}
else if (value is List<CompletionItem> sameNamedItems)
{
foreach (var item in sameNamedItems)
{
yield return item;
}
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly CompletionServiceWithProviders _completionServiceWithProviders;
public TestAccessor(CompletionServiceWithProviders completionServiceWithProviders)
=> _completionServiceWithProviders = completionServiceWithProviders;
internal ImmutableArray<CompletionProvider> GetAllProviders(ImmutableHashSet<string> roles)
=> _completionServiceWithProviders.GetAllProviders(roles);
internal Task<CompletionContext> GetContextAsync(
CompletionProvider provider,
Document document,
int position,
CompletionTrigger triggerInfo,
OptionSet options,
CancellationToken cancellationToken)
{
return _completionServiceWithProviders.GetContextAsync(
provider,
document,
position,
triggerInfo,
options,
defaultSpan: null,
cancellationToken);
}
}
}
}
| 1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpCreateServicesOnTextViewConnection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCreateServicesOnTextViewConnection([ImportMany] IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices)
: base(languageServices, LanguageNames.CSharp)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
[ImportMany] IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices)
: base(workspace, languageServices, LanguageNames.CSharp)
{
}
}
}
| 1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractCreateServicesOnTextViewConnection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
/// <summary>
/// Creates services on the first connection of an applicable subject buffer to an IWpfTextView.
/// This ensures the services are available by the time an open document or the interactive window needs them.
/// </summary>
internal abstract class AbstractCreateServicesOnTextViewConnection : IWpfTextViewConnectionListener
{
private readonly IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> _languageServices;
private readonly string _languageName;
private bool _initialized = false;
public AbstractCreateServicesOnTextViewConnection(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices, string languageName)
{
_languageServices = languageServices;
_languageName = languageName;
}
void IWpfTextViewConnectionListener.SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
if (!_initialized)
{
CreateServices(_languageName);
_initialized = true;
}
}
void IWpfTextViewConnectionListener.SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
/// <summary>
/// Must be invoked from the UI thread.
/// </summary>
private void CreateServices(string languageName)
{
var serviceTypeAssemblyQualifiedName = typeof(ISnippetInfoService).AssemblyQualifiedName;
foreach (var languageService in _languageServices)
{
if (languageService.Metadata.ServiceType == serviceTypeAssemblyQualifiedName &&
languageService.Metadata.Language == languageName)
{
_ = languageService.Value;
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.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
/// <summary>
/// Creates services on the first connection of an applicable subject buffer to an IWpfTextView.
/// This ensures the services are available by the time an open document or the interactive window needs them.
/// </summary>
internal abstract class AbstractCreateServicesOnTextViewConnection : IWpfTextViewConnectionListener
{
private readonly VisualStudioWorkspace _workspace;
private readonly IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> _languageServices;
private readonly string _languageName;
private bool _initialized = false;
public AbstractCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices,
string languageName)
{
_workspace = workspace;
_languageName = languageName;
_languageServices = languageServices;
}
void IWpfTextViewConnectionListener.SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
if (!_initialized)
{
CreateServicesOnUIThread();
CreateServicesInBackground();
_initialized = true;
}
}
void IWpfTextViewConnectionListener.SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
/// <summary>
/// Must be invoked from the UI thread.
/// </summary>
private void CreateServicesOnUIThread()
{
var serviceTypeAssemblyQualifiedName = typeof(ISnippetInfoService).AssemblyQualifiedName;
foreach (var languageService in _languageServices)
{
if (languageService.Metadata.ServiceType == serviceTypeAssemblyQualifiedName &&
languageService.Metadata.Language == _languageName)
{
_ = languageService.Value;
break;
}
}
}
private void CreateServicesInBackground()
{
_ = Task.Run(ImportCompletionProviders);
// Preload completion providers on a background thread since assembly loads can be slow
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1242321
void ImportCompletionProviders()
{
if (_workspace.Services.GetLanguageService<CompletionService>(_languageName) is CompletionServiceWithProviders service)
{
_ = service.GetImportedProviders().SelectAsArray(p => p.Value);
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCreateServicesOnTextViewConnection.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Export(GetType(IWpfTextViewConnectionListener))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<TextViewRole(PredefinedTextViewRoles.Interactive)>
Friend Class VisualBasicCreateServicesOnTextViewConnection
Inherits AbstractCreateServicesOnTextViewConnection
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> languageServices As IEnumerable(Of Lazy(Of ILanguageService, LanguageServiceMetadata)))
MyBase.New(languageServices, LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Export(GetType(IWpfTextViewConnectionListener))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<TextViewRole(PredefinedTextViewRoles.Interactive)>
Friend Class VisualBasicCreateServicesOnTextViewConnection
Inherits AbstractCreateServicesOnTextViewConnection
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(workspace As VisualStudioWorkspace, <ImportMany> languageServices As IEnumerable(Of Lazy(Of ILanguageService, LanguageServiceMetadata)))
MyBase.New(workspace, languageServices, languageName:=LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./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 | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>.
/// </summary>
public partial class FixAllContext
{
/// <summary>
/// Diagnostic provider to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>.
/// </summary>
public abstract class DiagnosticProvider
{
/// <summary>
/// Gets all the diagnostics to fix in the given document in a <see cref="FixAllContext"/>.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken);
/// <summary>
/// Gets all the project-level diagnostics to fix, i.e. diagnostics with no source location, in the given project in a <see cref="FixAllContext"/>.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken);
/// <summary>
/// Gets all the diagnostics to fix in the given project in a <see cref="FixAllContext"/>.
/// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken);
internal static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext)
{
var result = await GetDocumentDiagnosticsToFixWorkerAsync(fixAllContext).ConfigureAwait(false);
// Filter out any documents that we don't have any diagnostics for.
return result.Where(kvp => !kvp.Value.IsDefaultOrEmpty).ToImmutableDictionary();
static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixWorkerAsync(FixAllContext fixAllContext)
{
if (fixAllContext.State.DiagnosticProvider is FixAllState.FixMultipleDiagnosticProvider fixMultipleDiagnosticProvider)
{
return fixMultipleDiagnosticProvider.DocumentDiagnosticsMap;
}
using (Logger.LogBlock(
FunctionId.CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics,
FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
fixAllContext.CancellationToken))
{
return await FixAllContextHelper.GetDocumentDiagnosticsToFixAsync(fixAllContext).ConfigureAwait(false);
}
}
}
internal static async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(
FixAllContext fixAllContext)
{
using (Logger.LogBlock(
FunctionId.CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics,
FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
fixAllContext.CancellationToken))
{
var project = fixAllContext.Project;
if (project != null)
{
switch (fixAllContext.Scope)
{
case FixAllScope.Project:
var diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(project).ConfigureAwait(false);
var kvp = SpecializedCollections.SingletonEnumerable(KeyValuePairUtil.Create(project, diagnostics));
return ImmutableDictionary.CreateRange(kvp);
case FixAllScope.Solution:
var projectsAndDiagnostics = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
var tasks = project.Solution.Projects.Select(async p => new
{
Project = p,
Diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(p).ConfigureAwait(false)
}).ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var task in tasks)
{
var projectAndDiagnostics = await task.ConfigureAwait(false);
if (projectAndDiagnostics.Diagnostics.Any())
{
projectsAndDiagnostics[projectAndDiagnostics.Project] = projectAndDiagnostics.Diagnostics;
}
}
return projectsAndDiagnostics.ToImmutable();
}
}
return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.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;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>.
/// </summary>
public partial class FixAllContext
{
/// <summary>
/// Diagnostic provider to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>.
/// </summary>
public abstract class DiagnosticProvider
{
/// <summary>
/// Gets all the diagnostics to fix in the given document in a <see cref="FixAllContext"/>.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken);
/// <summary>
/// Gets all the project-level diagnostics to fix, i.e. diagnostics with no source location, in the given project in a <see cref="FixAllContext"/>.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken);
/// <summary>
/// Gets all the diagnostics to fix in the given project in a <see cref="FixAllContext"/>.
/// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project.
/// </summary>
public abstract Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken);
internal static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext)
{
var result = await GetDocumentDiagnosticsToFixWorkerAsync(fixAllContext).ConfigureAwait(false);
// Filter out any documents that we don't have any diagnostics for.
return result.Where(kvp => !kvp.Value.IsDefaultOrEmpty).ToImmutableDictionary();
static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixWorkerAsync(FixAllContext fixAllContext)
{
if (fixAllContext.State.DiagnosticProvider is FixAllState.FixMultipleDiagnosticProvider fixMultipleDiagnosticProvider)
{
return fixMultipleDiagnosticProvider.DocumentDiagnosticsMap;
}
using (Logger.LogBlock(
FunctionId.CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics,
FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
fixAllContext.CancellationToken))
{
return await FixAllContextHelper.GetDocumentDiagnosticsToFixAsync(fixAllContext).ConfigureAwait(false);
}
}
}
internal static async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(
FixAllContext fixAllContext)
{
using (Logger.LogBlock(
FunctionId.CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics,
FixAllLogger.CreateCorrelationLogMessage(fixAllContext.State.CorrelationId),
fixAllContext.CancellationToken))
{
var project = fixAllContext.Project;
if (project != null)
{
switch (fixAllContext.Scope)
{
case FixAllScope.Project:
var diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(project).ConfigureAwait(false);
var kvp = SpecializedCollections.SingletonEnumerable(KeyValuePairUtil.Create(project, diagnostics));
return ImmutableDictionary.CreateRange(kvp);
case FixAllScope.Solution:
var projectsAndDiagnostics = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
var tasks = project.Solution.Projects.Select(async p => new
{
Project = p,
Diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(p).ConfigureAwait(false)
}).ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var task in tasks)
{
var projectAndDiagnostics = await task.ConfigureAwait(false);
if (projectAndDiagnostics.Diagnostics.Any())
{
projectsAndDiagnostics[projectAndDiagnostics.Project] = projectAndDiagnostics.Diagnostics;
}
}
return projectsAndDiagnostics.ToImmutable();
}
}
return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MethodBlockTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class MethodBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSimpleSubDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo() 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub goo() 'Extra Comment
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclaration()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub New()
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub New()
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclarationForDesignerGeneratedClass()
VerifyStatementEndConstructApplied(
before:="<Microsoft.VisualBasic.CompilerServices.DesignerGenerated>
Class c1
Sub New()
Sub InitializeComponent()
End Sub
End Class",
beforeCaret:={2, -1},
after:=$"<Microsoft.VisualBasic.CompilerServices.DesignerGenerated>
Class c1
Sub New()
' {VBEditorResources.This_call_is_required_by_the_designer}
InitializeComponent()
' {VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call}
End Sub
Sub InitializeComponent()
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub New() 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub New() 'Extra Comment
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSimpleFunctionDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo() As Integer 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Function goo() As Integer 'Extra Comment
End Function
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub DoNotApplyForInterfaceFunction()
VerifyStatementEndConstructNotApplied(
text:="Interface IGoo
Function Goo() as Integer
End Interface",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySubInAModule()
VerifyStatementEndConstructApplied(
before:="Module C
Public Sub s
End Module",
beforeCaret:={1, -1},
after:="Module C
Public Sub s
End Sub
End Module",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySubWithParameters()
VerifyStatementEndConstructApplied(
before:="Module C
Private Sub s1(byval x as Integer, Optional y as Integer = 5)
End Module",
beforeCaret:={1, -1},
after:="Module C
Private Sub s1(byval x as Integer, Optional y as Integer = 5)
End Sub
End Module",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyFuncWithParameters()
VerifyStatementEndConstructApplied(
before:="Module C
Public function f(byval x as Integer,
byref y as string) as string
End Module",
beforeCaret:={2, -1},
after:="Module C
Public function f(byval x as Integer,
byref y as string) as string
End function
End Module",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyFuncNamedWithKeyWord()
VerifyStatementEndConstructApplied(
before:="Class C
private funCtion f1(Optional x as integer = 5) as [if]
End Class",
beforeCaret:={1, -1},
after:="Class C
private funCtion f1(Optional x as integer = 5) as [if]
End funCtion
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySharedOperator()
VerifyStatementEndConstructApplied(
before:="Class C
Public Shared Operator +(ByVal a As bar, ByVal b As bar) As bar
End Class",
beforeCaret:={1, -1},
after:="Class C
Public Shared Operator +(ByVal a As bar, ByVal b As bar) As bar
End Operator
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyRecommit()
VerifyStatementEndConstructNotApplied(
text:="Class C
Protected friend sub S
End sub
End Class",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidLocation01()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
Sub P
End Sub
End Class",
caret:={2, -1})
End Sub
<WorkItem(528961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528961")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInvalidLocation02()
VerifyStatementEndConstructApplied(
before:="Sub S",
beforeCaret:={0, -1},
after:="Sub S
End Sub",
afterCaret:={1, -1})
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class MethodBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSimpleSubDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo() 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub goo() 'Extra Comment
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclaration()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub New()
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub New()
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclarationForDesignerGeneratedClass()
VerifyStatementEndConstructApplied(
before:="<Microsoft.VisualBasic.CompilerServices.DesignerGenerated>
Class c1
Sub New()
Sub InitializeComponent()
End Sub
End Class",
beforeCaret:={2, -1},
after:=$"<Microsoft.VisualBasic.CompilerServices.DesignerGenerated>
Class c1
Sub New()
' {VBEditorResources.This_call_is_required_by_the_designer}
InitializeComponent()
' {VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call}
End Sub
Sub InitializeComponent()
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterConstructorDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub New() 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Sub New() 'Extra Comment
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSimpleFunctionDeclarationWithTrailingComment()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo() As Integer 'Extra Comment
End Class",
beforeCaret:={1, -1},
after:="Class c1
Function goo() As Integer 'Extra Comment
End Function
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub DoNotApplyForInterfaceFunction()
VerifyStatementEndConstructNotApplied(
text:="Interface IGoo
Function Goo() as Integer
End Interface",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySubInAModule()
VerifyStatementEndConstructApplied(
before:="Module C
Public Sub s
End Module",
beforeCaret:={1, -1},
after:="Module C
Public Sub s
End Sub
End Module",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySubWithParameters()
VerifyStatementEndConstructApplied(
before:="Module C
Private Sub s1(byval x as Integer, Optional y as Integer = 5)
End Module",
beforeCaret:={1, -1},
after:="Module C
Private Sub s1(byval x as Integer, Optional y as Integer = 5)
End Sub
End Module",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyFuncWithParameters()
VerifyStatementEndConstructApplied(
before:="Module C
Public function f(byval x as Integer,
byref y as string) as string
End Module",
beforeCaret:={2, -1},
after:="Module C
Public function f(byval x as Integer,
byref y as string) as string
End function
End Module",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyFuncNamedWithKeyWord()
VerifyStatementEndConstructApplied(
before:="Class C
private funCtion f1(Optional x as integer = 5) as [if]
End Class",
beforeCaret:={1, -1},
after:="Class C
private funCtion f1(Optional x as integer = 5) as [if]
End funCtion
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySharedOperator()
VerifyStatementEndConstructApplied(
before:="Class C
Public Shared Operator +(ByVal a As bar, ByVal b As bar) As bar
End Class",
beforeCaret:={1, -1},
after:="Class C
Public Shared Operator +(ByVal a As bar, ByVal b As bar) As bar
End Operator
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyRecommit()
VerifyStatementEndConstructNotApplied(
text:="Class C
Protected friend sub S
End sub
End Class",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidLocation01()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
Sub P
End Sub
End Class",
caret:={2, -1})
End Sub
<WorkItem(528961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528961")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInvalidLocation02()
VerifyStatementEndConstructApplied(
before:="Sub S",
beforeCaret:={0, -1},
after:="Sub S
End Sub",
afterCaret:={1, -1})
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Features/Core/Portable/TodoComments/DocumentAndComments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.TodoComments
{
internal readonly struct DocumentAndComments
{
public readonly DocumentId DocumentId;
public readonly ImmutableArray<TodoCommentData> Comments;
public DocumentAndComments(DocumentId documentId, ImmutableArray<TodoCommentData> comments)
{
DocumentId = documentId;
Comments = comments;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.TodoComments
{
internal readonly struct DocumentAndComments
{
public readonly DocumentId DocumentId;
public readonly ImmutableArray<TodoCommentData> Comments;
public DocumentAndComments(DocumentId documentId, ImmutableArray<TodoCommentData> comments)
{
DocumentId = documentId;
Comments = comments;
}
}
}
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/EditorConfig/EditorConfigNamingStyleParser.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal static partial class EditorConfigNamingStyleParser
{
/// <remarks>
/// The dictionary we get from the VS editorconfig API uses the same dictionary object if there are no changes, so we can cache based on dictionary
/// </remarks>
// TODO: revisit this cache. The assumption that the dictionary doesn't change in the exact instance is terribly fragile,
// and with the new .editorconfig support won't hold as well as we'd like: a single tree will have a stable instance but
// that won't necessarily be the same across files and projects.
private static readonly ConditionalWeakTable<IReadOnlyDictionary<string, string?>, NamingStylePreferences> _cache = new();
private static readonly object _cacheLock = new();
public static NamingStylePreferences GetNamingStylesFromDictionary(IReadOnlyDictionary<string, string?> rawOptions)
{
if (_cache.TryGetValue(rawOptions, out var value))
{
return value;
}
lock (_cacheLock)
{
if (!_cache.TryGetValue(rawOptions, out value))
{
value = ParseDictionary(rawOptions);
_cache.Add(rawOptions, value);
}
return value;
}
}
public static NamingStylePreferences ParseDictionary(IReadOnlyDictionary<string, string?> allRawConventions)
{
var symbolSpecifications = ArrayBuilder<SymbolSpecification>.GetInstance();
var namingStyles = ArrayBuilder<NamingStyle>.GetInstance();
var namingRules = ArrayBuilder<SerializableNamingRule>.GetInstance();
var ruleNames = new Dictionary<(Guid symbolSpecificationID, Guid namingStyleID, ReportDiagnostic enforcementLevel), string>();
var trimmedDictionary = TrimDictionary(allRawConventions);
foreach (var namingRuleTitle in GetRuleTitles(trimmedDictionary))
{
if (TryGetSymbolSpec(namingRuleTitle, trimmedDictionary, out var symbolSpec) &&
TryGetNamingStyleData(namingRuleTitle, trimmedDictionary, out var namingStyle) &&
TryGetSerializableNamingRule(namingRuleTitle, symbolSpec, namingStyle, trimmedDictionary, out var serializableNamingRule))
{
symbolSpecifications.Add(symbolSpec);
namingStyles.Add(namingStyle);
namingRules.Add(serializableNamingRule);
var ruleKey = (serializableNamingRule.SymbolSpecificationID, serializableNamingRule.NamingStyleID, serializableNamingRule.EnforcementLevel);
if (ruleNames.TryGetValue(ruleKey, out var existingName))
{
// For duplicated rules, only preserve the one with a name that would sort first
var ordinalIgnoreCaseOrdering = StringComparer.OrdinalIgnoreCase.Compare(namingRuleTitle, existingName);
if (ordinalIgnoreCaseOrdering > 0)
{
continue;
}
else if (ordinalIgnoreCaseOrdering == 0)
{
var ordinalOrdering = StringComparer.Ordinal.Compare(namingRuleTitle, existingName);
if (ordinalOrdering > 0)
{
continue;
}
}
}
ruleNames[ruleKey] = namingRuleTitle;
}
}
var preferences = new NamingStylePreferences(
symbolSpecifications.ToImmutableAndFree(),
namingStyles.ToImmutableAndFree(),
namingRules.ToImmutableAndFree());
// Deterministically order the naming style rules according to the symbols matched by the rule. The rules
// are applied in order; later rules are only relevant if earlier rules fail to specify an order.
//
// 1. If the modifiers required by rule 'x' are a strict superset of the modifiers required by rule 'y',
// then rule 'x' is evaluated before rule 'y'.
// 2. If the accessibilities allowed by rule 'x' are a strict subset of the accessibilities allowed by rule
// 'y', then rule 'x' is evaluated before rule 'y'.
// 3. If the set of symbols matched by rule 'x' are a strict subset of the symbols matched by rule 'y', then
// rule 'x' is evaluated before rule 'y'.
//
// If none of the above produces an order between two rules 'x' and 'y', then the rules are ordered
// according to their name, first by OrdinalIgnoreCase and finally by Ordinal.
//
// Historical note: rules used to be ordered by their position in the .editorconfig file. However, this
// relied on an implementation detail of the .editorconfig parser which is not preserved by all
// implementations. In a review of .editorconfig files in the wild, the rules applied in this section were
// the closest deterministic match for the files without having any reliance on order. For any pair of rules
// which a user has trouble ordering, the intersection of the two rules can be broken out into a new rule
// will always match earlier than the broader rules it was derived from.
var orderedRules = preferences.Rules.NamingRules
.OrderBy(rule => rule, NamingRuleModifierListComparer.Instance)
.ThenBy(rule => rule, NamingRuleAccessibilityListComparer.Instance)
.ThenBy(rule => rule, NamingRuleSymbolListComparer.Instance)
.ThenBy(rule => ruleNames[(rule.SymbolSpecification.ID, rule.NamingStyle.ID, rule.EnforcementLevel)], StringComparer.OrdinalIgnoreCase)
.ThenBy(rule => ruleNames[(rule.SymbolSpecification.ID, rule.NamingStyle.ID, rule.EnforcementLevel)], StringComparer.Ordinal);
return new NamingStylePreferences(
preferences.SymbolSpecifications,
preferences.NamingStyles,
orderedRules.SelectAsArray(
rule => new SerializableNamingRule
{
SymbolSpecificationID = rule.SymbolSpecification.ID,
NamingStyleID = rule.NamingStyle.ID,
EnforcementLevel = rule.EnforcementLevel,
}));
}
private static Dictionary<string, string?> TrimDictionary(IReadOnlyDictionary<string, string?> allRawConventions)
{
// Keys have been lowercased, but values have not. Because values here reference key
// names we need any comparisons to ignore case.
// For example, to make a naming style called "Pascal_Case_style" match up correctly
// with the key "dotnet_naming_style.pascal_case_style.capitalization", we have to
// ignore casing for that lookup.
var trimmedDictionary = new Dictionary<string, string?>(allRawConventions.Count, AnalyzerConfigOptions.KeyComparer);
foreach (var item in allRawConventions)
{
var key = item.Key.Trim();
var value = item.Value;
trimmedDictionary[key] = value;
}
return trimmedDictionary;
}
private static IEnumerable<string> GetRuleTitles(IReadOnlyDictionary<string, string?> allRawConventions)
=> (from kvp in allRawConventions
where kvp.Key.Trim().StartsWith("dotnet_naming_rule.", StringComparison.Ordinal)
let nameSplit = kvp.Key.Split('.')
where nameSplit.Length == 3
select nameSplit[1])
.Distinct();
private abstract class NamingRuleSubsetComparer : IComparer<NamingRule>
{
protected NamingRuleSubsetComparer()
{
}
public int Compare(NamingRule x, NamingRule y)
{
var firstIsSubset = FirstIsSubset(in x, in y);
var secondIsSubset = FirstIsSubset(in y, in x);
if (firstIsSubset)
{
return secondIsSubset ? 0 : -1;
}
else
{
return secondIsSubset ? 1 : 0;
}
}
/// <summary>
/// Determines if <paramref name="x"/> matches a subset of the symbols matched by <paramref name="y"/>. The
/// implementation determines which properties of <see cref="NamingRule"/> are considered for this
/// evaluation. The subset relation does not necessarily indicate a proper subset.
/// </summary>
/// <param name="x">The first naming rule.</param>
/// <param name="y">The second naming rule.</param>
/// <returns><see langword="true"/> if <paramref name="x"/> matches a subset of the symbols matched by
/// <paramref name="y"/> on some implementation-defined properties; otherwise, <see langword="false"/>.</returns>
protected abstract bool FirstIsSubset(in NamingRule x, in NamingRule y);
}
private sealed class NamingRuleAccessibilityListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleAccessibilityListComparer Instance = new();
private NamingRuleAccessibilityListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
foreach (var accessibility in x.SymbolSpecification.ApplicableAccessibilityList)
{
if (!y.SymbolSpecification.ApplicableAccessibilityList.Contains(accessibility))
{
return false;
}
}
return true;
}
}
private sealed class NamingRuleModifierListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleModifierListComparer Instance = new();
private NamingRuleModifierListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
// Since modifiers are "match all", a subset of symbols is matched by a superset of modifiers
foreach (var modifier in y.SymbolSpecification.RequiredModifierList)
{
if (modifier.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsStatic
|| modifier.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsReadOnly)
{
if (x.SymbolSpecification.RequiredModifierList.Any(x => x.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsConst))
{
// 'const' implies both 'readonly' and 'static'
continue;
}
}
if (!x.SymbolSpecification.RequiredModifierList.Contains(modifier))
{
return false;
}
}
return true;
}
}
private sealed class NamingRuleSymbolListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleSymbolListComparer Instance = new();
private NamingRuleSymbolListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
foreach (var symbolKind in x.SymbolSpecification.ApplicableSymbolKindList)
{
if (!y.SymbolSpecification.ApplicableSymbolKindList.Contains(symbolKind))
{
return false;
}
}
return true;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal static partial class EditorConfigNamingStyleParser
{
/// <remarks>
/// The dictionary we get from the VS editorconfig API uses the same dictionary object if there are no changes, so we can cache based on dictionary
/// </remarks>
// TODO: revisit this cache. The assumption that the dictionary doesn't change in the exact instance is terribly fragile,
// and with the new .editorconfig support won't hold as well as we'd like: a single tree will have a stable instance but
// that won't necessarily be the same across files and projects.
private static readonly ConditionalWeakTable<IReadOnlyDictionary<string, string?>, NamingStylePreferences> _cache = new();
private static readonly object _cacheLock = new();
public static NamingStylePreferences GetNamingStylesFromDictionary(IReadOnlyDictionary<string, string?> rawOptions)
{
if (_cache.TryGetValue(rawOptions, out var value))
{
return value;
}
lock (_cacheLock)
{
if (!_cache.TryGetValue(rawOptions, out value))
{
value = ParseDictionary(rawOptions);
_cache.Add(rawOptions, value);
}
return value;
}
}
public static NamingStylePreferences ParseDictionary(IReadOnlyDictionary<string, string?> allRawConventions)
{
var symbolSpecifications = ArrayBuilder<SymbolSpecification>.GetInstance();
var namingStyles = ArrayBuilder<NamingStyle>.GetInstance();
var namingRules = ArrayBuilder<SerializableNamingRule>.GetInstance();
var ruleNames = new Dictionary<(Guid symbolSpecificationID, Guid namingStyleID, ReportDiagnostic enforcementLevel), string>();
var trimmedDictionary = TrimDictionary(allRawConventions);
foreach (var namingRuleTitle in GetRuleTitles(trimmedDictionary))
{
if (TryGetSymbolSpec(namingRuleTitle, trimmedDictionary, out var symbolSpec) &&
TryGetNamingStyleData(namingRuleTitle, trimmedDictionary, out var namingStyle) &&
TryGetSerializableNamingRule(namingRuleTitle, symbolSpec, namingStyle, trimmedDictionary, out var serializableNamingRule))
{
symbolSpecifications.Add(symbolSpec);
namingStyles.Add(namingStyle);
namingRules.Add(serializableNamingRule);
var ruleKey = (serializableNamingRule.SymbolSpecificationID, serializableNamingRule.NamingStyleID, serializableNamingRule.EnforcementLevel);
if (ruleNames.TryGetValue(ruleKey, out var existingName))
{
// For duplicated rules, only preserve the one with a name that would sort first
var ordinalIgnoreCaseOrdering = StringComparer.OrdinalIgnoreCase.Compare(namingRuleTitle, existingName);
if (ordinalIgnoreCaseOrdering > 0)
{
continue;
}
else if (ordinalIgnoreCaseOrdering == 0)
{
var ordinalOrdering = StringComparer.Ordinal.Compare(namingRuleTitle, existingName);
if (ordinalOrdering > 0)
{
continue;
}
}
}
ruleNames[ruleKey] = namingRuleTitle;
}
}
var preferences = new NamingStylePreferences(
symbolSpecifications.ToImmutableAndFree(),
namingStyles.ToImmutableAndFree(),
namingRules.ToImmutableAndFree());
// Deterministically order the naming style rules according to the symbols matched by the rule. The rules
// are applied in order; later rules are only relevant if earlier rules fail to specify an order.
//
// 1. If the modifiers required by rule 'x' are a strict superset of the modifiers required by rule 'y',
// then rule 'x' is evaluated before rule 'y'.
// 2. If the accessibilities allowed by rule 'x' are a strict subset of the accessibilities allowed by rule
// 'y', then rule 'x' is evaluated before rule 'y'.
// 3. If the set of symbols matched by rule 'x' are a strict subset of the symbols matched by rule 'y', then
// rule 'x' is evaluated before rule 'y'.
//
// If none of the above produces an order between two rules 'x' and 'y', then the rules are ordered
// according to their name, first by OrdinalIgnoreCase and finally by Ordinal.
//
// Historical note: rules used to be ordered by their position in the .editorconfig file. However, this
// relied on an implementation detail of the .editorconfig parser which is not preserved by all
// implementations. In a review of .editorconfig files in the wild, the rules applied in this section were
// the closest deterministic match for the files without having any reliance on order. For any pair of rules
// which a user has trouble ordering, the intersection of the two rules can be broken out into a new rule
// will always match earlier than the broader rules it was derived from.
var orderedRules = preferences.Rules.NamingRules
.OrderBy(rule => rule, NamingRuleModifierListComparer.Instance)
.ThenBy(rule => rule, NamingRuleAccessibilityListComparer.Instance)
.ThenBy(rule => rule, NamingRuleSymbolListComparer.Instance)
.ThenBy(rule => ruleNames[(rule.SymbolSpecification.ID, rule.NamingStyle.ID, rule.EnforcementLevel)], StringComparer.OrdinalIgnoreCase)
.ThenBy(rule => ruleNames[(rule.SymbolSpecification.ID, rule.NamingStyle.ID, rule.EnforcementLevel)], StringComparer.Ordinal);
return new NamingStylePreferences(
preferences.SymbolSpecifications,
preferences.NamingStyles,
orderedRules.SelectAsArray(
rule => new SerializableNamingRule
{
SymbolSpecificationID = rule.SymbolSpecification.ID,
NamingStyleID = rule.NamingStyle.ID,
EnforcementLevel = rule.EnforcementLevel,
}));
}
private static Dictionary<string, string?> TrimDictionary(IReadOnlyDictionary<string, string?> allRawConventions)
{
// Keys have been lowercased, but values have not. Because values here reference key
// names we need any comparisons to ignore case.
// For example, to make a naming style called "Pascal_Case_style" match up correctly
// with the key "dotnet_naming_style.pascal_case_style.capitalization", we have to
// ignore casing for that lookup.
var trimmedDictionary = new Dictionary<string, string?>(allRawConventions.Count, AnalyzerConfigOptions.KeyComparer);
foreach (var item in allRawConventions)
{
var key = item.Key.Trim();
var value = item.Value;
trimmedDictionary[key] = value;
}
return trimmedDictionary;
}
private static IEnumerable<string> GetRuleTitles(IReadOnlyDictionary<string, string?> allRawConventions)
=> (from kvp in allRawConventions
where kvp.Key.Trim().StartsWith("dotnet_naming_rule.", StringComparison.Ordinal)
let nameSplit = kvp.Key.Split('.')
where nameSplit.Length == 3
select nameSplit[1])
.Distinct();
private abstract class NamingRuleSubsetComparer : IComparer<NamingRule>
{
protected NamingRuleSubsetComparer()
{
}
public int Compare(NamingRule x, NamingRule y)
{
var firstIsSubset = FirstIsSubset(in x, in y);
var secondIsSubset = FirstIsSubset(in y, in x);
if (firstIsSubset)
{
return secondIsSubset ? 0 : -1;
}
else
{
return secondIsSubset ? 1 : 0;
}
}
/// <summary>
/// Determines if <paramref name="x"/> matches a subset of the symbols matched by <paramref name="y"/>. The
/// implementation determines which properties of <see cref="NamingRule"/> are considered for this
/// evaluation. The subset relation does not necessarily indicate a proper subset.
/// </summary>
/// <param name="x">The first naming rule.</param>
/// <param name="y">The second naming rule.</param>
/// <returns><see langword="true"/> if <paramref name="x"/> matches a subset of the symbols matched by
/// <paramref name="y"/> on some implementation-defined properties; otherwise, <see langword="false"/>.</returns>
protected abstract bool FirstIsSubset(in NamingRule x, in NamingRule y);
}
private sealed class NamingRuleAccessibilityListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleAccessibilityListComparer Instance = new();
private NamingRuleAccessibilityListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
foreach (var accessibility in x.SymbolSpecification.ApplicableAccessibilityList)
{
if (!y.SymbolSpecification.ApplicableAccessibilityList.Contains(accessibility))
{
return false;
}
}
return true;
}
}
private sealed class NamingRuleModifierListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleModifierListComparer Instance = new();
private NamingRuleModifierListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
// Since modifiers are "match all", a subset of symbols is matched by a superset of modifiers
foreach (var modifier in y.SymbolSpecification.RequiredModifierList)
{
if (modifier.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsStatic
|| modifier.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsReadOnly)
{
if (x.SymbolSpecification.RequiredModifierList.Any(x => x.ModifierKindWrapper == SymbolSpecification.ModifierKindEnum.IsConst))
{
// 'const' implies both 'readonly' and 'static'
continue;
}
}
if (!x.SymbolSpecification.RequiredModifierList.Contains(modifier))
{
return false;
}
}
return true;
}
}
private sealed class NamingRuleSymbolListComparer : NamingRuleSubsetComparer
{
internal static readonly NamingRuleSymbolListComparer Instance = new();
private NamingRuleSymbolListComparer()
{
}
protected override bool FirstIsSubset(in NamingRule x, in NamingRule y)
{
foreach (var symbolKind in x.SymbolSpecification.ApplicableSymbolKindList)
{
if (!y.SymbolSpecification.ApplicableSymbolKindList.Contains(symbolKind))
{
return false;
}
}
return true;
}
}
}
}
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.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.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Friend Class ElasticTriviaFormattingRule
Inherits BaseFormattingRule
Friend Const Name As String = "VisualBasic Elastic Trivia Formatting Rule"
Public Sub New()
End Sub
Public Overrides Sub AddSuppressOperationsSlow(list As List(Of SuppressOperation), node As SyntaxNode, ByRef nextOperation As NextSuppressOperationAction)
nextOperation.Invoke()
End Sub
Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction)
nextOperation.Invoke()
If node.Kind = SyntaxKind.ObjectMemberInitializer Then
Dim initializer = DirectCast(node, ObjectMemberInitializerSyntax)
If initializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
AddIndentBlockOperation(list,
initializer.OpenBraceToken,
initializer.CloseBraceToken.GetPreviousToken(),
[option]:=IndentBlockOption.RelativePosition)
list.Add(FormattingOperations.CreateIndentBlockOperation(
initializer.CloseBraceToken, initializer.CloseBraceToken,
indentationDelta:=0,
[option]:=IndentBlockOption.RelativePosition))
End If
End If
If node.Kind = SyntaxKind.ObjectCollectionInitializer Then
Dim collectionInitializer = DirectCast(node, ObjectCollectionInitializerSyntax)
If collectionInitializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
Dim initializer = collectionInitializer.Initializer
AddIndentBlockOperation(list,
initializer.OpenBraceToken,
initializer.CloseBraceToken.GetPreviousToken(),
[option]:=IndentBlockOption.RelativePosition)
list.Add(FormattingOperations.CreateIndentBlockOperation(
initializer.CloseBraceToken, initializer.CloseBraceToken,
indentationDelta:=0,
[option]:=IndentBlockOption.RelativePosition))
End If
End If
End Sub
Public Overrides Sub AddAlignTokensOperationsSlow(list As List(Of AlignTokensOperation),
node As SyntaxNode,
ByRef nextOperation As NextAlignTokensOperationAction)
nextOperation.Invoke()
If node.Kind = SyntaxKind.ObjectMemberInitializer Then
Dim initializer = DirectCast(node, ObjectMemberInitializerSyntax)
If initializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
list.Add(New AlignTokensOperation(
initializer.WithKeyword,
SpecializedCollections.SingletonEnumerable(initializer.CloseBraceToken),
[option]:=AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine))
End If
End If
If node.Kind = SyntaxKind.ObjectCollectionInitializer Then
Dim collectionInitializer = DirectCast(node, ObjectCollectionInitializerSyntax)
If collectionInitializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
list.Add(New AlignTokensOperation(
collectionInitializer.FromKeyword,
SpecializedCollections.SingletonEnumerable(collectionInitializer.Initializer.CloseBraceToken),
[option]:=AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine))
End If
End If
End Sub
Public Overrides Function GetAdjustSpacesOperationSlow(ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustSpacesOperation) As AdjustSpacesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke(previousToken, currentToken)
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke(previousToken, currentToken)
If operation IsNot Nothing AndAlso operation.Option = AdjustSpacesOption.ForceSpaces Then
Return operation
End If
' remove blank lines between parameter lists and implements clauses
If currentToken.Kind = SyntaxKind.ImplementsKeyword AndAlso
(previousToken.GetAncestor(Of MethodStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of EventStatementSyntax)() IsNot Nothing) Then
Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces)
End If
' handle comma separated lists in implements clauses
If previousToken.GetAncestor(Of ImplementsClauseSyntax)() IsNot Nothing AndAlso currentToken.Kind = SyntaxKind.CommaToken Then
Return FormattingOperations.CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces)
End If
If currentToken.Kind = SyntaxKind.OpenBraceToken AndAlso
currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustSpacesOperation(1,
[option]:=AdjustSpacesOption.ForceSpaces)
End If
Return operation
End Function
Public Overrides Function GetAdjustNewLinesOperationSlow(
ByRef previousToken As SyntaxToken,
ByRef currentToken As SyntaxToken,
ByRef nextOperation As NextGetAdjustNewLinesOperation) As AdjustNewLinesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke(previousToken, currentToken)
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke(previousToken, currentToken)
If operation IsNot Nothing AndAlso operation.Option = AdjustNewLinesOption.ForceLines Then
Return operation
End If
If currentToken.Kind = SyntaxKind.DotToken AndAlso
currentToken.Parent.Kind = SyntaxKind.NamedFieldInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If previousToken.Kind = SyntaxKind.OpenBraceToken AndAlso
previousToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
previousToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If previousToken.Kind = SyntaxKind.CommaToken AndAlso
previousToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
previousToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Kind = SyntaxKind.OpenBraceToken AndAlso
currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.CollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Kind = SyntaxKind.CloseBraceToken Then
If currentToken.Parent.Kind = SyntaxKind.ObjectMemberInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
End If
' put attributes in its own line if it is top level attribute
Dim attributeNode = TryCast(previousToken.Parent, AttributeListSyntax)
If attributeNode IsNot Nothing AndAlso TypeOf attributeNode.Parent Is StatementSyntax AndAlso
attributeNode.GreaterThanToken = previousToken AndAlso currentToken.Kind <> SyntaxKind.LessThanToken Then
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines)
End If
If Not previousToken.IsLastTokenOfStatement() Then
Return operation
End If
' The previous token may end a statement, but it could be in a lambda inside parens.
If currentToken.Kind = SyntaxKind.CloseParenToken AndAlso
TypeOf currentToken.Parent Is ParenthesizedExpressionSyntax Then
Return operation
End If
If AfterLastInheritsOrImplements(previousToken, currentToken) Then
If Not TypeOf currentToken.Parent Is EndBlockStatementSyntax Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
End If
If AfterLastImportStatement(previousToken, currentToken) Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
Dim lines = LineBreaksAfter(previousToken, currentToken)
If Not lines.HasValue Then
If TypeOf previousToken.Parent Is XmlNodeSyntax Then
' make sure next statement starts on its own line if previous statement ends with xml literals
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(Math.Max(If(operation Is Nothing, 1, operation.Line), 0), AdjustNewLinesOption.PreserveLines)
End If
If lines = 0 Then
Return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(lines.Value, AdjustNewLinesOption.ForceLines)
End Function
Private Shared Function AfterLastImportStatement(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
' in between two imports
If nextToken.Kind = SyntaxKind.ImportsKeyword Then
Return False
End If
' current one is not import statement
If Not TypeOf token.Parent Is NameSyntax Then
Return False
End If
Dim [imports] = token.GetAncestor(Of ImportsStatementSyntax)()
If [imports] Is Nothing Then
Return False
End If
Return True
End Function
Private Shared Function AfterLastInheritsOrImplements(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
Dim inheritsOrImplements = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Dim nextInheritsOrImplements = nextToken.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Return inheritsOrImplements IsNot Nothing AndAlso nextInheritsOrImplements Is Nothing
End Function
Private Shared Function IsBeginStatement(Of TStatement As StatementSyntax, TBlock As StatementSyntax)(node As StatementSyntax) As Boolean
Return TryCast(node, TStatement) IsNot Nothing AndAlso TryCast(node.Parent, TBlock) IsNot Nothing
End Function
Private Shared Function IsEndBlockStatement(node As StatementSyntax) As Boolean
Return TryCast(node, EndBlockStatementSyntax) IsNot Nothing OrElse
TryCast(node, LoopStatementSyntax) IsNot Nothing OrElse
TryCast(node, NextStatementSyntax) IsNot Nothing
End Function
Private Shared Function LineBreaksAfter(previousToken As SyntaxToken, currentToken As SyntaxToken) As Integer?
If currentToken.Kind = SyntaxKind.None OrElse
previousToken.Kind = SyntaxKind.None Then
Return 0
End If
Dim previousStatement = previousToken.GetAncestor(Of StatementSyntax)()
Dim currentStatement = currentToken.GetAncestor(Of StatementSyntax)()
If previousStatement Is Nothing OrElse currentStatement Is Nothing Then
Return Nothing
End If
If TopLevelStatement(previousStatement) AndAlso Not TopLevelStatement(currentStatement) Then
Return GetActualLines(previousToken, currentToken, 1)
End If
' Early out of accessors, we don't force more lines between them.
If previousStatement.Kind = SyntaxKind.EndSetStatement OrElse
previousStatement.Kind = SyntaxKind.EndGetStatement OrElse
previousStatement.Kind = SyntaxKind.EndAddHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRemoveHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRaiseEventStatement Then
Return Nothing
End If
' Blank line after an end block, unless it's followed by another end or an else
If IsEndBlockStatement(previousStatement) Then
If IsEndBlockStatement(currentStatement) OrElse
currentStatement.Kind = SyntaxKind.ElseIfStatement OrElse
currentStatement.Kind = SyntaxKind.ElseStatement Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
' Blank line _before_ a block, unless it's the first thing in a type.
If IsBeginStatement(Of MethodStatementSyntax, MethodBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SubNewStatementSyntax, ConstructorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of OperatorStatementSyntax, OperatorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of PropertyStatementSyntax, PropertyBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EventStatementSyntax, EventBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TypeStatementSyntax, TypeBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EnumStatementSyntax, EnumBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of NamespaceStatementSyntax, NamespaceBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of DoStatementSyntax, DoLoopBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForEachStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of IfStatementSyntax, MultiLineIfBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SelectStatementSyntax, SelectBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SyncLockStatementSyntax, SyncLockBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TryStatementSyntax, TryBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of UsingStatementSyntax, UsingBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WhileStatementSyntax, WhileBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WithStatementSyntax, WithBlockSyntax)(currentStatement) Then
If TypeOf previousStatement Is NamespaceStatementSyntax OrElse
TypeOf previousStatement Is TypeStatementSyntax OrElse
TypeOf previousStatement Is IfStatementSyntax Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
Return Nothing
End Function
Private Shared Function GetActualLines(token1 As SyntaxToken, token2 As SyntaxToken, lines As Integer, Optional leadingBlankLines As Integer = 0) As Integer
If leadingBlankLines = 0 Then
Return Math.Max(lines, 0)
End If
' see whether first non whitespace trivia after previous member is comment or not
Dim list = token1.TrailingTrivia.Concat(token2.LeadingTrivia)
Dim firstNonWhitespaceTrivia = list.FirstOrDefault(Function(t) Not t.IsWhitespaceOrEndOfLine())
If firstNonWhitespaceTrivia.IsKind(SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentTrivia) Then
Dim totalLines = GetNumberOfLines(list)
Dim blankLines = GetNumberOfLines(list.TakeWhile(Function(t) t <> firstNonWhitespaceTrivia))
If totalLines < lines Then
Dim afterCommentWithBlank = (totalLines - blankLines) + leadingBlankLines
Return Math.Max(If(lines > afterCommentWithBlank, lines, afterCommentWithBlank), 0)
End If
If blankLines < leadingBlankLines Then
Return Math.Max(totalLines - blankLines + leadingBlankLines, 0)
End If
Return Math.Max(totalLines, 0)
End If
Return Math.Max(lines, 0)
End Function
Private Shared Function GetNumberOfLines(list As IEnumerable(Of SyntaxTrivia)) As Integer
Return list.Sum(Function(t) t.ToFullString().Replace(vbCrLf, vbCr).OfType(Of Char).Count(Function(c) SyntaxFacts.IsNewLine(c)))
End Function
Private Shared Function TopLevelStatement(statement As StatementSyntax) As Boolean
Return TypeOf statement Is MethodStatementSyntax OrElse
TypeOf statement Is SubNewStatementSyntax OrElse
TypeOf statement Is LambdaHeaderSyntax OrElse
TypeOf statement Is OperatorStatementSyntax OrElse
TypeOf statement Is PropertyStatementSyntax OrElse
TypeOf statement Is EventStatementSyntax OrElse
TypeOf statement Is TypeStatementSyntax OrElse
TypeOf statement Is EnumStatementSyntax OrElse
TypeOf statement Is NamespaceStatementSyntax
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Friend Class ElasticTriviaFormattingRule
Inherits BaseFormattingRule
Friend Const Name As String = "VisualBasic Elastic Trivia Formatting Rule"
Public Sub New()
End Sub
Public Overrides Sub AddSuppressOperationsSlow(list As List(Of SuppressOperation), node As SyntaxNode, ByRef nextOperation As NextSuppressOperationAction)
nextOperation.Invoke()
End Sub
Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction)
nextOperation.Invoke()
If node.Kind = SyntaxKind.ObjectMemberInitializer Then
Dim initializer = DirectCast(node, ObjectMemberInitializerSyntax)
If initializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
AddIndentBlockOperation(list,
initializer.OpenBraceToken,
initializer.CloseBraceToken.GetPreviousToken(),
[option]:=IndentBlockOption.RelativePosition)
list.Add(FormattingOperations.CreateIndentBlockOperation(
initializer.CloseBraceToken, initializer.CloseBraceToken,
indentationDelta:=0,
[option]:=IndentBlockOption.RelativePosition))
End If
End If
If node.Kind = SyntaxKind.ObjectCollectionInitializer Then
Dim collectionInitializer = DirectCast(node, ObjectCollectionInitializerSyntax)
If collectionInitializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
Dim initializer = collectionInitializer.Initializer
AddIndentBlockOperation(list,
initializer.OpenBraceToken,
initializer.CloseBraceToken.GetPreviousToken(),
[option]:=IndentBlockOption.RelativePosition)
list.Add(FormattingOperations.CreateIndentBlockOperation(
initializer.CloseBraceToken, initializer.CloseBraceToken,
indentationDelta:=0,
[option]:=IndentBlockOption.RelativePosition))
End If
End If
End Sub
Public Overrides Sub AddAlignTokensOperationsSlow(list As List(Of AlignTokensOperation),
node As SyntaxNode,
ByRef nextOperation As NextAlignTokensOperationAction)
nextOperation.Invoke()
If node.Kind = SyntaxKind.ObjectMemberInitializer Then
Dim initializer = DirectCast(node, ObjectMemberInitializerSyntax)
If initializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
list.Add(New AlignTokensOperation(
initializer.WithKeyword,
SpecializedCollections.SingletonEnumerable(initializer.CloseBraceToken),
[option]:=AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine))
End If
End If
If node.Kind = SyntaxKind.ObjectCollectionInitializer Then
Dim collectionInitializer = DirectCast(node, ObjectCollectionInitializerSyntax)
If collectionInitializer.GetLeadingTrivia().HasAnyWhitespaceElasticTrivia() Then
list.Add(New AlignTokensOperation(
collectionInitializer.FromKeyword,
SpecializedCollections.SingletonEnumerable(collectionInitializer.Initializer.CloseBraceToken),
[option]:=AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine))
End If
End If
End Sub
Public Overrides Function GetAdjustSpacesOperationSlow(ByRef previousToken As SyntaxToken, ByRef currentToken As SyntaxToken, ByRef nextOperation As NextGetAdjustSpacesOperation) As AdjustSpacesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke(previousToken, currentToken)
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke(previousToken, currentToken)
If operation IsNot Nothing AndAlso operation.Option = AdjustSpacesOption.ForceSpaces Then
Return operation
End If
' remove blank lines between parameter lists and implements clauses
If currentToken.Kind = SyntaxKind.ImplementsKeyword AndAlso
(previousToken.GetAncestor(Of MethodStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of EventStatementSyntax)() IsNot Nothing) Then
Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces)
End If
' handle comma separated lists in implements clauses
If previousToken.GetAncestor(Of ImplementsClauseSyntax)() IsNot Nothing AndAlso currentToken.Kind = SyntaxKind.CommaToken Then
Return FormattingOperations.CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces)
End If
If currentToken.Kind = SyntaxKind.OpenBraceToken AndAlso
currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustSpacesOperation(1,
[option]:=AdjustSpacesOption.ForceSpaces)
End If
Return operation
End Function
Public Overrides Function GetAdjustNewLinesOperationSlow(
ByRef previousToken As SyntaxToken,
ByRef currentToken As SyntaxToken,
ByRef nextOperation As NextGetAdjustNewLinesOperation) As AdjustNewLinesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke(previousToken, currentToken)
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke(previousToken, currentToken)
If operation IsNot Nothing AndAlso operation.Option = AdjustNewLinesOption.ForceLines Then
Return operation
End If
If currentToken.Kind = SyntaxKind.DotToken AndAlso
currentToken.Parent.Kind = SyntaxKind.NamedFieldInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If previousToken.Kind = SyntaxKind.OpenBraceToken AndAlso
previousToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
previousToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If previousToken.Kind = SyntaxKind.CommaToken AndAlso
previousToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
previousToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Kind = SyntaxKind.OpenBraceToken AndAlso
currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.CollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Kind = SyntaxKind.CloseBraceToken Then
If currentToken.Parent.Kind = SyntaxKind.ObjectMemberInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
If currentToken.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
currentToken.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer Then
Return New AdjustNewLinesOperation(line:=1,
[option]:=AdjustNewLinesOption.ForceLines)
End If
End If
' put attributes in its own line if it is top level attribute
Dim attributeNode = TryCast(previousToken.Parent, AttributeListSyntax)
If attributeNode IsNot Nothing AndAlso TypeOf attributeNode.Parent Is StatementSyntax AndAlso
attributeNode.GreaterThanToken = previousToken AndAlso currentToken.Kind <> SyntaxKind.LessThanToken Then
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines)
End If
If Not previousToken.IsLastTokenOfStatement() Then
Return operation
End If
' The previous token may end a statement, but it could be in a lambda inside parens.
If currentToken.Kind = SyntaxKind.CloseParenToken AndAlso
TypeOf currentToken.Parent Is ParenthesizedExpressionSyntax Then
Return operation
End If
If AfterLastInheritsOrImplements(previousToken, currentToken) Then
If Not TypeOf currentToken.Parent Is EndBlockStatementSyntax Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
End If
If AfterLastImportStatement(previousToken, currentToken) Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
Dim lines = LineBreaksAfter(previousToken, currentToken)
If Not lines.HasValue Then
If TypeOf previousToken.Parent Is XmlNodeSyntax Then
' make sure next statement starts on its own line if previous statement ends with xml literals
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(Math.Max(If(operation Is Nothing, 1, operation.Line), 0), AdjustNewLinesOption.PreserveLines)
End If
If lines = 0 Then
Return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(lines.Value, AdjustNewLinesOption.ForceLines)
End Function
Private Shared Function AfterLastImportStatement(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
' in between two imports
If nextToken.Kind = SyntaxKind.ImportsKeyword Then
Return False
End If
' current one is not import statement
If Not TypeOf token.Parent Is NameSyntax Then
Return False
End If
Dim [imports] = token.GetAncestor(Of ImportsStatementSyntax)()
If [imports] Is Nothing Then
Return False
End If
Return True
End Function
Private Shared Function AfterLastInheritsOrImplements(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
Dim inheritsOrImplements = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Dim nextInheritsOrImplements = nextToken.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Return inheritsOrImplements IsNot Nothing AndAlso nextInheritsOrImplements Is Nothing
End Function
Private Shared Function IsBeginStatement(Of TStatement As StatementSyntax, TBlock As StatementSyntax)(node As StatementSyntax) As Boolean
Return TryCast(node, TStatement) IsNot Nothing AndAlso TryCast(node.Parent, TBlock) IsNot Nothing
End Function
Private Shared Function IsEndBlockStatement(node As StatementSyntax) As Boolean
Return TryCast(node, EndBlockStatementSyntax) IsNot Nothing OrElse
TryCast(node, LoopStatementSyntax) IsNot Nothing OrElse
TryCast(node, NextStatementSyntax) IsNot Nothing
End Function
Private Shared Function LineBreaksAfter(previousToken As SyntaxToken, currentToken As SyntaxToken) As Integer?
If currentToken.Kind = SyntaxKind.None OrElse
previousToken.Kind = SyntaxKind.None Then
Return 0
End If
Dim previousStatement = previousToken.GetAncestor(Of StatementSyntax)()
Dim currentStatement = currentToken.GetAncestor(Of StatementSyntax)()
If previousStatement Is Nothing OrElse currentStatement Is Nothing Then
Return Nothing
End If
If TopLevelStatement(previousStatement) AndAlso Not TopLevelStatement(currentStatement) Then
Return GetActualLines(previousToken, currentToken, 1)
End If
' Early out of accessors, we don't force more lines between them.
If previousStatement.Kind = SyntaxKind.EndSetStatement OrElse
previousStatement.Kind = SyntaxKind.EndGetStatement OrElse
previousStatement.Kind = SyntaxKind.EndAddHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRemoveHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRaiseEventStatement Then
Return Nothing
End If
' Blank line after an end block, unless it's followed by another end or an else
If IsEndBlockStatement(previousStatement) Then
If IsEndBlockStatement(currentStatement) OrElse
currentStatement.Kind = SyntaxKind.ElseIfStatement OrElse
currentStatement.Kind = SyntaxKind.ElseStatement Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
' Blank line _before_ a block, unless it's the first thing in a type.
If IsBeginStatement(Of MethodStatementSyntax, MethodBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SubNewStatementSyntax, ConstructorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of OperatorStatementSyntax, OperatorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of PropertyStatementSyntax, PropertyBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EventStatementSyntax, EventBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TypeStatementSyntax, TypeBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EnumStatementSyntax, EnumBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of NamespaceStatementSyntax, NamespaceBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of DoStatementSyntax, DoLoopBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForEachStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of IfStatementSyntax, MultiLineIfBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SelectStatementSyntax, SelectBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SyncLockStatementSyntax, SyncLockBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TryStatementSyntax, TryBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of UsingStatementSyntax, UsingBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WhileStatementSyntax, WhileBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WithStatementSyntax, WithBlockSyntax)(currentStatement) Then
If TypeOf previousStatement Is NamespaceStatementSyntax OrElse
TypeOf previousStatement Is TypeStatementSyntax OrElse
TypeOf previousStatement Is IfStatementSyntax Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
Return Nothing
End Function
Private Shared Function GetActualLines(token1 As SyntaxToken, token2 As SyntaxToken, lines As Integer, Optional leadingBlankLines As Integer = 0) As Integer
If leadingBlankLines = 0 Then
Return Math.Max(lines, 0)
End If
' see whether first non whitespace trivia after previous member is comment or not
Dim list = token1.TrailingTrivia.Concat(token2.LeadingTrivia)
Dim firstNonWhitespaceTrivia = list.FirstOrDefault(Function(t) Not t.IsWhitespaceOrEndOfLine())
If firstNonWhitespaceTrivia.IsKind(SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentTrivia) Then
Dim totalLines = GetNumberOfLines(list)
Dim blankLines = GetNumberOfLines(list.TakeWhile(Function(t) t <> firstNonWhitespaceTrivia))
If totalLines < lines Then
Dim afterCommentWithBlank = (totalLines - blankLines) + leadingBlankLines
Return Math.Max(If(lines > afterCommentWithBlank, lines, afterCommentWithBlank), 0)
End If
If blankLines < leadingBlankLines Then
Return Math.Max(totalLines - blankLines + leadingBlankLines, 0)
End If
Return Math.Max(totalLines, 0)
End If
Return Math.Max(lines, 0)
End Function
Private Shared Function GetNumberOfLines(list As IEnumerable(Of SyntaxTrivia)) As Integer
Return list.Sum(Function(t) t.ToFullString().Replace(vbCrLf, vbCr).OfType(Of Char).Count(Function(c) SyntaxFacts.IsNewLine(c)))
End Function
Private Shared Function TopLevelStatement(statement As StatementSyntax) As Boolean
Return TypeOf statement Is MethodStatementSyntax OrElse
TypeOf statement Is SubNewStatementSyntax OrElse
TypeOf statement Is LambdaHeaderSyntax OrElse
TypeOf statement Is OperatorStatementSyntax OrElse
TypeOf statement Is PropertyStatementSyntax OrElse
TypeOf statement Is EventStatementSyntax OrElse
TypeOf statement Is TypeStatementSyntax OrElse
TypeOf statement Is EnumStatementSyntax OrElse
TypeOf statement Is NamespaceStatementSyntax
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSendToInteractive.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSendToInteractive : AbstractInteractiveWindowTest
{
private const string FileName = "Program.cs";
public CSharpSendToInteractive(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync();
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ConsoleApplication, Microsoft.CodeAnalysis.LanguageNames.CSharp);
VisualStudio.Editor.SetText(@"using System;
namespace TestProj
{
public class Program
{
public static void Main(string[] args)
{
/* 1 */int x = 1;/* 2 */
/* 3 */int y = 2;
int z = 3;/* 4 */
/* 5 */ string a = ""alpha"";
string b = ""x *= 4; "";/* 6 */
/* 7 */int j = 7;/* 8 */
}
}
public class C
{
public string M()
{
return ""C.M()"";
}
}
}
");
VisualStudio.Editor.Activate();
VisualStudio.InteractiveWindow.SubmitText("using System;");
}
[WpfFact]
public void SendSingleLineSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 1");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 1 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 2 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int x = 1;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("x.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"1\"");
}
[WpfFact]
public void SendMultipleLineSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 2");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 3 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 4 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int z = 3;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("y.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"2\"");
VisualStudio.InteractiveWindow.SubmitText("z.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"3\"");
}
[WpfFact]
public void SendMultipleLineBlockSelectedSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.SubmitText("int x = 1;");
VisualStudio.InteractiveWindow.InsertCode("// scenario 3");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 5 */", charsOffset: 6);
VisualStudio.Editor.PlaceCaret("/* 6 */", charsOffset: -3, extendSelection: true, selectBlock: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput(". x *= 4;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("a + \"s\"");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"alphas\"");
VisualStudio.InteractiveWindow.SubmitText("b");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("4");
}
[WpfFact]
public void SendToInteractiveWithKeyboardShortcut()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 4");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 7 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 8 */", charsOffset: -1, extendSelection: true);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.E), Ctrl(VirtualKey.E));
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int j = 7;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("j.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"7\"");
}
[WpfFact]
public void ExecuteSingleLineSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 5");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 1 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 2 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 5");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("1");
}
[WpfFact]
public void ExecuteMultipleLineSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 6");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 3 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 4 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 6");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("y");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("2");
VisualStudio.InteractiveWindow.SubmitText("z");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("3");
}
[WpfFact]
public void ExecuteMultipleLineBlockSelectedSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.SubmitText("int x = 1;");
VisualStudio.InteractiveWindow.InsertCode("// scenario 7");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 5 */", charsOffset: 6);
VisualStudio.Editor.PlaceCaret("/* 6 */", charsOffset: -3, extendSelection: true, selectBlock: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 7");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("a");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"alpha\"");
VisualStudio.InteractiveWindow.SubmitText("b");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("4");
}
[WpfFact]
public void ExecuteInInteractiveWithKeyboardShortcut()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 8");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 7 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 8 */", charsOffset: -1, extendSelection: true);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.E), Ctrl(VirtualKey.E));
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 8");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("j");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("7");
}
[WpfFact]
public void AddAssemblyReferenceAndTypesToInteractive()
{
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("#r \"System.Numerics\"");
VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(new System.Numerics.BigInteger(42));");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("42");
VisualStudio.InteractiveWindow.SubmitText("public class MyClass { public string MyFunc() { return \"MyClass.MyFunc()\"; } }");
VisualStudio.InteractiveWindow.SubmitText("(new MyClass()).MyFunc()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"MyClass.MyFunc()\"");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler);
}
[WpfFact]
public void ResetInteractiveFromProjectAndVerify()
{
var assembly = new ProjectUtils.AssemblyReference("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddMetadataReference(assembly, project);
VisualStudio.SolutionExplorer.SelectItem(ProjectName);
VisualStudio.ExecuteCommand(WellKnownCommandNames.ProjectAndSolutionContextMenus_Project_ResetCSharpInteractiveFromProject);
// Waiting for a long operation: build + reset from project
VisualStudio.InteractiveWindow.WaitForReplOutput("using TestProj;");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("(new TestProj.C()).M()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"C.M()\"");
VisualStudio.InteractiveWindow.SubmitText("System.Windows.Forms.Form f = new System.Windows.Forms.Form(); f.Text = \"goo\";");
VisualStudio.InteractiveWindow.SubmitText("f.Text");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"goo\"");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSendToInteractive : AbstractInteractiveWindowTest
{
private const string FileName = "Program.cs";
public CSharpSendToInteractive(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync();
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ConsoleApplication, Microsoft.CodeAnalysis.LanguageNames.CSharp);
VisualStudio.Editor.SetText(@"using System;
namespace TestProj
{
public class Program
{
public static void Main(string[] args)
{
/* 1 */int x = 1;/* 2 */
/* 3 */int y = 2;
int z = 3;/* 4 */
/* 5 */ string a = ""alpha"";
string b = ""x *= 4; "";/* 6 */
/* 7 */int j = 7;/* 8 */
}
}
public class C
{
public string M()
{
return ""C.M()"";
}
}
}
");
VisualStudio.Editor.Activate();
VisualStudio.InteractiveWindow.SubmitText("using System;");
}
[WpfFact]
public void SendSingleLineSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 1");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 1 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 2 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int x = 1;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("x.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"1\"");
}
[WpfFact]
public void SendMultipleLineSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 2");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 3 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 4 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int z = 3;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("y.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"2\"");
VisualStudio.InteractiveWindow.SubmitText("z.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"3\"");
}
[WpfFact]
public void SendMultipleLineBlockSelectedSubmissionToInteractive()
{
VisualStudio.InteractiveWindow.SubmitText("int x = 1;");
VisualStudio.InteractiveWindow.InsertCode("// scenario 3");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 5 */", charsOffset: 6);
VisualStudio.Editor.PlaceCaret("/* 6 */", charsOffset: -3, extendSelection: true, selectBlock: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplOutput(". x *= 4;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("a + \"s\"");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"alphas\"");
VisualStudio.InteractiveWindow.SubmitText("b");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("4");
}
[WpfFact]
public void SendToInteractiveWithKeyboardShortcut()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 4");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 7 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 8 */", charsOffset: -1, extendSelection: true);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.E), Ctrl(VirtualKey.E));
VisualStudio.InteractiveWindow.WaitForLastReplOutput("int j = 7;");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("j.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("\"7\"");
}
[WpfFact]
public void ExecuteSingleLineSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 5");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 1 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 2 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 5");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("1");
}
[WpfFact]
public void ExecuteMultipleLineSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 6");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 3 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 4 */", charsOffset: -1, extendSelection: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 6");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("y");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("2");
VisualStudio.InteractiveWindow.SubmitText("z");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("3");
}
[WpfFact]
public void ExecuteMultipleLineBlockSelectedSubmissionInInteractiveWhilePreservingReplSubmissionBuffer()
{
VisualStudio.InteractiveWindow.SubmitText("int x = 1;");
VisualStudio.InteractiveWindow.InsertCode("// scenario 7");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 5 */", charsOffset: 6);
VisualStudio.Editor.PlaceCaret("/* 6 */", charsOffset: -3, extendSelection: true, selectBlock: true);
VisualStudio.ExecuteCommand(WellKnownCommandNames.InteractiveConsole_ExecuteInInteractive);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 7");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("a");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"alpha\"");
VisualStudio.InteractiveWindow.SubmitText("b");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("4");
}
[WpfFact]
public void ExecuteInInteractiveWithKeyboardShortcut()
{
VisualStudio.InteractiveWindow.InsertCode("// scenario 8");
var project = new Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, FileName);
VisualStudio.Editor.PlaceCaret("/* 7 */", charsOffset: 1);
VisualStudio.Editor.PlaceCaret("/* 8 */", charsOffset: -1, extendSelection: true);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.E), Ctrl(VirtualKey.E));
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("// scenario 8");
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("j");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("7");
}
[WpfFact]
public void AddAssemblyReferenceAndTypesToInteractive()
{
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.SubmitText("#r \"System.Numerics\"");
VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(new System.Numerics.BigInteger(42));");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("42");
VisualStudio.InteractiveWindow.SubmitText("public class MyClass { public string MyFunc() { return \"MyClass.MyFunc()\"; } }");
VisualStudio.InteractiveWindow.SubmitText("(new MyClass()).MyFunc()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"MyClass.MyFunc()\"");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler);
}
[WpfFact]
public void ResetInteractiveFromProjectAndVerify()
{
var assembly = new ProjectUtils.AssemblyReference("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddMetadataReference(assembly, project);
VisualStudio.SolutionExplorer.SelectItem(ProjectName);
VisualStudio.ExecuteCommand(WellKnownCommandNames.ProjectAndSolutionContextMenus_Project_ResetCSharpInteractiveFromProject);
// Waiting for a long operation: build + reset from project
VisualStudio.InteractiveWindow.WaitForReplOutput("using TestProj;");
VisualStudio.InteractiveWindow.SubmitText("x");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS0103");
VisualStudio.InteractiveWindow.SubmitText("(new TestProj.C()).M()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"C.M()\"");
VisualStudio.InteractiveWindow.SubmitText("System.Windows.Forms.Form f = new System.Windows.Forms.Form(); f.Text = \"goo\";");
VisualStudio.InteractiveWindow.SubmitText("f.Text");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"goo\"");
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler);
}
}
}
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Scripting/VisualBasic/VisualBasicScript.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 System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Scripting
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting
''' <summary>
''' A factory for creating and running Visual Basic scripts.
''' </summary>
Public NotInheritable Class VisualBasicScript
Private Sub New()
End Sub
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of T)
Return Script.CreateInitialScript(Of T)(VisualBasicScriptCompiler.Instance, SourceText.From(If(code, String.Empty)), options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of Object)
Return Create(Of Object)(code, options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of T))
Return Create(Of T)(code, options, globals?.GetType()).RunAsync(globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of Object))
Return RunAsync(Of Object)(code, options, globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of T)
Return RunAsync(Of T)(code, options, globals, cancellationToken).GetEvaluationResultAsync()
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of Object)
Return EvaluateAsync(Of Object)(code, Nothing, globals, cancellationToken)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Scripting
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting
''' <summary>
''' A factory for creating and running Visual Basic scripts.
''' </summary>
Public NotInheritable Class VisualBasicScript
Private Sub New()
End Sub
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of T)
Return Script.CreateInitialScript(Of T)(VisualBasicScriptCompiler.Instance, SourceText.From(If(code, String.Empty)), options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Create a new Visual Basic script.
''' </summary>
Public Shared Function Create(code As String,
Optional options As ScriptOptions = Nothing,
Optional globalsType As Type = Nothing,
Optional assemblyLoader As InteractiveAssemblyLoader = Nothing) As Script(Of Object)
Return Create(Of Object)(code, options, globalsType, assemblyLoader)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of T))
Return Create(Of T)(code, options, globals?.GetType()).RunAsync(globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script.
''' </summary>
Public Shared Function RunAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of ScriptState(Of Object))
Return RunAsync(Of Object)(code, options, globals, cancellationToken)
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(Of T)(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of T)
Return RunAsync(Of T)(code, options, globals, cancellationToken).GetEvaluationResultAsync()
End Function
''' <summary>
''' Run a Visual Basic script and return its resulting value.
''' </summary>
Public Shared Function EvaluateAsync(code As String,
Optional options As ScriptOptions = Nothing,
Optional globals As Object = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As Task(Of Object)
Return EvaluateAsync(Of Object)(code, Nothing, globals, cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,448 | MEF import completion providers in background | Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | genlu | 2021-08-05T23:14:11Z | 2021-08-06T00:33:20Z | 75a39a2831b2ca2f91968ad4afedea41e457f3fb | 0a8b7797ac7976f6b7152e5f7c1de44259b5a0ad | MEF import completion providers in background. Fix [AB#1242321](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1242321) | ./src/Compilers/VisualBasic/Portable/DocumentationComments/DocumentationCommentIDVisitor.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class DocumentationCommentIdVisitor
Inherits VisualBasicSymbolVisitor(Of StringBuilder, Object)
Public Shared ReadOnly Instance As New DocumentationCommentIdVisitor()
Private Sub New()
End Sub
Public Overrides Function DefaultVisit(symbol As Symbol, builder As StringBuilder) As Object
Return Nothing
End Function
Public Overrides Function VisitNamespace(symbol As NamespaceSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "N:")
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "E:")
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "M:")
End Function
Public Overrides Function VisitField(symbol As FieldSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "F:")
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "P:")
End Function
Public Overrides Function VisitNamedType(symbol As NamedTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Public Overrides Function VisitErrorType(symbol As ErrorTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Private Shared Function VisitSymbolUsingPrefix(symbol As Symbol, builder As StringBuilder, prefix As String) As Object
builder.Append(prefix)
PartVisitor.Instance.Visit(symbol, builder)
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class DocumentationCommentIdVisitor
Inherits VisualBasicSymbolVisitor(Of StringBuilder, Object)
Public Shared ReadOnly Instance As New DocumentationCommentIdVisitor()
Private Sub New()
End Sub
Public Overrides Function DefaultVisit(symbol As Symbol, builder As StringBuilder) As Object
Return Nothing
End Function
Public Overrides Function VisitNamespace(symbol As NamespaceSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "N:")
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "E:")
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "M:")
End Function
Public Overrides Function VisitField(symbol As FieldSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "F:")
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "P:")
End Function
Public Overrides Function VisitNamedType(symbol As NamedTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "T:")
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Public Overrides Function VisitErrorType(symbol As ErrorTypeSymbol, builder As StringBuilder) As Object
Return VisitSymbolUsingPrefix(symbol, builder, "!:")
End Function
Private Shared Function VisitSymbolUsingPrefix(symbol As Symbol, builder As StringBuilder, prefix As String) As Object
builder.Append(prefix)
PartVisitor.Instance.Visit(symbol, builder)
Return Nothing
End Function
End Class
End Namespace
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.